Database Manual / Reference / mongosh Methods / Databases

db.getCollection() (mongosh method方法)

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 mongosh itself, such as names that begin with _ or that match a database shell method.该方法对于名称可能与mongosh本身交互的集合或视图非常有用,例如以_开头的名称或与数据库shell方法匹配的名称。

The db.getCollection() method has the following parameter:db.getCollection()方法有以下参数:

Parameter参数Type类型Description描述
namestring字符串The name of the collection.集合的名称。

Compatibility兼容性

This method is available in deployments hosted in the following environments:此方法在以下环境中托管的部署中可用:

  • MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud:云中MongoDB部署的完全托管服务

Note

This command is supported in all MongoDB Atlas clusters. 所有MongoDB Atlas集群都支持此命令。For information on Atlas support for all commands, see Unsupported Commands.有关Atlas支持所有命令的信息,请参阅不支持的命令

  • MongoDB Enterprise: The subscription-based, self-managed version of MongoDB:MongoDB的基于订阅的自我管理版本
  • MongoDB Community: The source-available, free-to-use, and self-managed version of MongoDB:MongoDB的源代码可用、免费使用和自我管理版本

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 db.collection.insertOne().如果集合不存在,MongoDB会隐式创建它,作为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.auth()的名称冲突,前面的示例需要使用db.getCollection("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方法。