Options
All
  • Public
  • Public/Protected
  • All
Menu

Class Collection<TSchema>

The Collection class is an internal class that embodies a MongoDB collection allowing for insert/update/remove/find and other command operation on that MongoDB collection.

COLLECTION Cannot directly be instantiated

example
const MongoClient = require('mongodb').MongoClient;
const test = require('assert');
// Connection url
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'test';
// Connect using MongoClient
MongoClient.connect(url, function(err, client) {
  // Create a collection we want to drop later
  const col = client.db(dbName).collection('createIndexExample1');
  // Show that duplicate records got dropped
  col.find({}).toArray(function(err, items) {
    expect(err).to.not.exist;
    test.equal(4, items.length);
    client.close();
  });
});

Type parameters

Hierarchy

  • Collection

Index

Constructors

constructor

Properties

s

internal

Accessors

bsonOptions

collectionName

  • get collectionName(): string

dbName

  • get dbName(): string

hint

  • get hint(): undefined | Hint
  • set hint(v: undefined | Hint): void

logger

namespace

  • get namespace(): string
  • The namespace of this collection, in the format ${this.dbName}.${this.collectionName}

    Returns string

readConcern

  • The current readConcern of the collection. If not explicitly defined for this collection, will be inherited from the parent DB

    Returns undefined | ReadConcern

readPreference

  • The current readPreference of the collection. If not explicitly defined for this collection, will be inherited from the parent DB

    Returns undefined | ReadPreference

writeConcern

  • The current writeConcern of the collection. If not explicitly defined for this collection, will be inherited from the parent DB

    Returns undefined | WriteConcern

Methods

aggregate

  • Execute an aggregation framework pipeline against the collection, needs MongoDB >= 2.2

    Type parameters

    • T = TSchema

    Parameters

    • pipeline: Document[] = []

      An array of aggregation pipelines to execute

    • Optional options: AggregateOptions

      Optional settings for the command

    Returns AggregationCursor<T>

bulkWrite

  • Perform a bulkWrite operation without a fluent API

    Legal operation types are

     { insertOne: { document: { a: 1 } } }
    
     { updateOne: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } }
    
     { updateMany: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } }
    
     { updateMany: { filter: {}, update: {$set: {"a.$[i].x": 5}}, arrayFilters: [{ "i.x": 5 }]} }
    
     { deleteOne: { filter: {c:1} } }
    
     { deleteMany: { filter: {c:1} } }
    
     { replaceOne: { filter: {c:3}, replacement: {c:4}, upsert:true} }
    

    Please note that raw operations are no longer accepted as of driver version 4.0.

    If documents passed in do not contain the _id field, one will be added to each of the documents missing it by the driver, mutating the document. This behavior can be overridden by setting the forceServerObjectId flag.

    throws

    MongoDriverError if operations is not an array

    Parameters

    Returns Promise<BulkWriteResult>

  • Parameters

    Returns void

  • Parameters

    Returns Promise<BulkWriteResult>

  • Parameters

    Returns void

count

  • An estimated count of matching documents in the db to a filter.

    NOTE: This method has been deprecated, since it does not provide an accurate count of the documents in a collection. To obtain an accurate count of documents in the collection, use {@link Collection#countDocuments| countDocuments}. To obtain an estimated count of all documents in the collection, use {@link Collection#estimatedDocumentCount| estimatedDocumentCount}.

    deprecated

    use {@link Collection#countDocuments| countDocuments} or {@link Collection#estimatedDocumentCount| estimatedDocumentCount} instead

    Returns Promise<number>

  • Parameters

    Returns void

  • Parameters

    Returns Promise<number>

  • Parameters

    Returns void

  • Parameters

    Returns Promise<number>

  • Parameters

    Returns void | Promise<number>

countDocuments

createIndex

  • Creates an index on the db and collection collection.

    example
    const collection = client.db('foo').collection('bar');
    
    await collection.createIndex({ a: 1, b: -1 });
    
    // Alternate syntax for { c: 1, d: -1 } that ensures order of indexes
    await collection.createIndex([ [c, 1], [d, -1] ]);
    
    // Equivalent to { e: 1 }
    await collection.createIndex('e');
    
    // Equivalent to { f: 1, g: 1 }
    await collection.createIndex(['f', 'g'])
    
    // Equivalent to { h: 1, i: -1 }
    await collection.createIndex([ { h: 1 }, { i: -1 } ]);
    
    // Equivalent to { j: 1, k: -1, l: 2d }
    await collection.createIndex(['j', ['k', -1], { l: '2d' }])
    

    Parameters

    • indexSpec: IndexSpecification

      The field name or index specification to create an index for

    Returns Promise<string>

  • Parameters

    Returns void

  • Parameters

    Returns Promise<string>

  • Parameters

    Returns void

createIndexes

  • Creates multiple indexes in the collection, this method is only supported for MongoDB 2.6 or higher. Earlier version of MongoDB will throw a command not supported error.

    Note: Unlike {@link Collection#createIndex| createIndex}, this function takes in raw index specifications. Index specifications are defined here.

    example
    const collection = client.db('foo').collection('bar');
    await collection.createIndexes([
      // Simple index on field fizz
      {
        key: { fizz: 1 },
      }
      // wildcard index
      {
        key: { '$**': 1 }
      },
      // named index on darmok and jalad
      {
        key: { darmok: 1, jalad: -1 }
        name: 'tanagra'
      }
    ]);
    

    Parameters

    Returns Promise<string[]>

  • Parameters

    Returns void

  • Parameters

    Returns Promise<string[]>

  • Parameters

    Returns void

deleteMany

deleteOne

distinct

drop

dropIndex

dropIndexes

estimatedDocumentCount

find

findOne

findOneAndDelete

findOneAndReplace

findOneAndUpdate

getLogger

indexExists

  • indexExists(indexes: string | string[]): Promise<boolean>
  • indexExists(indexes: string | string[], callback: Callback<boolean>): void
  • indexExists(indexes: string | string[], options: IndexInformationOptions): Promise<boolean>
  • indexExists(indexes: string | string[], options: IndexInformationOptions, callback: Callback<boolean>): void

indexInformation

indexes

initializeOrderedBulkOp

initializeUnorderedBulkOp

insert

  • Inserts a single document or a an array of documents into MongoDB. If documents passed in do not contain the _id field, one will be added to each of the documents missing it by the driver, mutating the document. This behavior can be overridden by setting the forceServerObjectId flag.

    deprecated

    Use insertOne, insertMany or bulkWrite instead.

    Parameters

    Returns void | Promise<InsertManyResult<TSchema>>

insertMany

insertOne

isCapped

listIndexes

mapReduce

options

remove

  • Remove documents.

    deprecated

    use deleteOne, deleteMany or bulkWrite

    Parameters

    • selector: Filter<TSchema>

      The selector for the update operation.

    • options: DeleteOptions

      Optional settings for the command

    • callback: Callback<any>

      An optional callback, a Promise will be returned if none is provided

    Returns void | Promise<DeleteResult>

rename

replaceOne

stats

update

  • Updates documents.

    deprecated

    use updateOne, updateMany or bulkWrite

    Parameters

    • selector: Filter<TSchema>

      The selector for the update operation.

    • update: UpdateFilter<TSchema>

      The update operations to be applied to the documents

    • options: UpdateOptions

      Optional settings for the command

    • callback: Callback<Document>

      An optional callback, a Promise will be returned if none is provided

    Returns void | Promise<UpdateResult>

updateMany

updateOne

watch

  • Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this collection.

    since

    3.0.0

    Type parameters

    • TLocal = TSchema

    Parameters

    Returns ChangeStream<TLocal>

Generated using TypeDoc