翻译或纠错本页面

db.getCollection()

On this page

Definition

db.getCollection(name)

Returns a collection object that is functionally equivalent to using the db.<collectionName> syntax. The method is useful for a collection whose name might interact with the shell itself, such as names that begin with _ or that match a database shell method.

The db.getCollection() method has the following parameter:

Parameter Type Description
name string The name of the collection.

Behavior

The db.getCollection() object can access any collection methods.

The collection specified may or may not exist on the server. If the collection does not exist, MongoDB creates it implicitly as part of write operations like db.collection.insertOne().

Example

The following example uses db.getCollection() to access the auth collection and insert a document into it.

var authColl = db.getCollection("auth")

authColl.insertOne(
   {
       usrName : "John Doe",
       usrDept : "Sales",
       usrTitle : "Executive Account Manager",
       authLevel : 4,
       authDept : [ "Sales", "Customers"]
   }
)

This returns:

{
   "acknowledged" : true,
   "insertedId" : ObjectId("569525e144fe66d60b772763")
}

The previous example requires the use of db.getCollection("auth") because of a name conflict with the database method db.auth(). Calling db.auth directly to perform an insert operation would reference the db.auth() method and would error.

The following example attempts the same operation, but without using the db.getCollection() method:

db.auth.insertOne(
   {
       usrName : "John Doe",
       usrDept : "Sales",
       usrTitle : "Executive Account Manager",
       authLevel : 4,
       authDept : [ "Sales", "Customers"]
   }
)

The operation errors as db.auth() method has no insertOne method.