定义
db.getCollection(name)Returns a collection or a view object that is functionally equivalent to using the
db.<collectionName>syntax. The method is useful for a collection or a view whose name might interact withmongoshitself, such as names that begin with_or that match a database shell method.The
db.getCollection()method has the following parameter:Parameter类型说明name字符串
集合的名称。
兼容性
此方法可用于以下环境中托管的部署:
- MongoDB Atlas:用于云中 MongoDB 部署的完全托管服务
注意
所有 MongoDB Atlas 集群都支持此命令。有关 Atlas 对所有命令的支持的信息,请参阅不支持的命令。
MongoDB Enterprise:基于订阅、自我管理的 MongoDB 版本
MongoDB Community:源代码可用、免费使用且可自行管理的 MongoDB 版本
行为
The db.getCollection() object can access any collection methods.
指定的集合可能存在于服务器上,也可能不存在。如果该集合不存在,则 MongoDB 会将其作为写入操作(如 db.collection.insertOne())的一部分隐式创建。
例子
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"] } )
此操作将返回:
{ "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"] } )
操作错误,因为 db.auth() 方法没有 insertOne 方法。
提示