db.getCollection()

在本页面

Definition

  • db. getCollection(* name *)
    • 返回功能上等效于db.<collectionName>语法的collectionview对象。该方法对于名称可能与mongo shell 本身交互的集合或视图很有用,例如以_开头或与数据库 Shell 方法匹配的名称。

db.getCollection()方法具有以下参数:

ParameterTypeDescription
namestring集合的名称。

Behavior

db.getCollection()对象可以访问任何collection methods

指定的集合可能在服务器上存在或不存在。如果该集合不存在,则 MongoDB 像db.collection.insertOne()一样隐式地将其创建为write operations的一部分。

Example

下面的示例使用db.getCollection()访问auth集合并将文档插入其中。

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")
}

上一个示例需要使用db.getCollection("auth"),因为它与数据库方法db.auth()发生名称冲突。直接调用db.auth以执行插入操作将引用db.auth()方法,并且会出错。

下面的示例尝试相同的操作,但不使用db.getCollection()方法:

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

db.auth()方法的操作错误没有insertOne方法。