db.getCollection()

Definition

  • db.getCollection(name)
  • Returns a collection or a view objectthat is functionally equivalent to using the db.<collectionName>syntax. The method is useful for a collection or a view whose namemight interact with the mongo shell itself, such as namesthat begin with _ or that match a database shell method.

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

ParameterTypeDescriptionnamestringThe name of the collection.

Behavior

The db.getCollection() object can access anycollection methods.

The collection specified may or may not exist on the server. If the collectiondoes not exist, MongoDB creates it implicitly as part ofwrite operations likedb.collection.insertOne().

Example

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

  1. var authColl = db.getCollection("auth")
  2.  
  3. authColl.insertOne(
  4. {
  5. usrName : "John Doe",
  6. usrDept : "Sales",
  7. usrTitle : "Executive Account Manager",
  8. authLevel : 4,
  9. authDept : [ "Sales", "Customers"]
  10. }
  11. )

This returns:

  1. {
  2. "acknowledged" : true,
  3. "insertedId" : ObjectId("569525e144fe66d60b772763")
  4. }

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

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

  1. db.auth.insertOne(
  2. {
  3. usrName : "John Doe",
  4. usrDept : "Sales",
  5. usrTitle : "Executive Account Manager",
  6. authLevel : 4,
  7. authDept : [ "Sales", "Customers"]
  8. }
  9. )

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

See also

Collection Methods