db.getCollection()
On this page本页内容
Definition定义
db.getCollection(name)-
Returns a collection or a view object that is functionally equivalent to using the返回一个集合或视图对象,该对象在功能上等效于使用数据库db.<collectionName>syntax.db.<collectionName>语法。The method is useful for a collection or a view whose name might interact with该方法适用于名称可能与mongoshitself, such as names that begin with_or that match a database shell method.mongosh本身交互的集合或视图,例如以_开头的名称或与数据库shell方法匹配的名称。Thedb.getCollection()method has the following parameter:db.getCollection()方法具有以下参数:Parameter参数Type类型Description描述namestring The name of the collection.集合的名称。
Behavior行为
The db.getCollection() object can access any collection methods.db.getCollection()对象可以访问任何集合方法。
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 如果集合不存在,MongoDB会隐式创建它,作为db.collection.insertOne().db.collection.insertOne()等写入操作的一部分。
Example实例
The following example uses 以下示例使用db.getCollection() to access the auth collection and insert a document into it.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")
}
The previous example requires the use of 上一个示例要求使用db.getCollection("auth") because of a name conflict with the database method db.auth(). db.getCollection("auth"),因为名称与数据库方法db.auth()冲突。Calling 直接调用db.auth directly to perform an insert operation would reference the db.auth() method and would error.db.auth来执行插入操作会引用db.auth()方法并出错。
The following example attempts the same operation, but without using the 以下示例尝试相同的操作,但不使用db.getCollection() method:db.getCollection()方法:
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.db.auth()方法没有insertOne方法,操作出错。