Docs HomeMongoDB Manual

db.getCollectionNames()

Definition定义

db.getCollectionNames()

Returns an array containing the names of all collections and views in the current database, or if running with access control, the names of the collections according to user's privilege. 返回一个数组,该数组包含当前数据库中所有集合和视图的名称,如果使用访问控制运行,则返回根据用户权限的集合名称。For details, see Required Access.有关详细信息,请参阅必需访问权限

Required Access所需访问权限

The db.getCollectionNames() is equivalent to:db.getCollectionNames()等效于:

db.runCommand(
{
listCollections: 1.0,
authorizedCollections: true,
nameOnly: true
}
)
  • For users with the required access (privileges that grant listCollections action on the database), the method lists the names of all collections for the database.对于具有所需访问权限(对数据库授予listCollections操作的权限)的用户,该方法将列出数据库的所有集合的名称。
  • For users without the required access, the method lists only the collections for which the users has privileges. 对于没有所需访问权限的用户,该方法只列出用户具有权限的集合。For example, if a user has find on a specific collection in a database, the method would return just that collection.例如,如果用户在数据库中在特定的集合上find,则该方法将只返回该集合。

Behavior行为

Client Disconnection客户端断开连接

Starting in MongoDB 4.2, if the client that issued db.getCollectionNames() disconnects before the operation completes, MongoDB marks db.getCollectionNames() for termination using killOp.从MongoDB 4.2开始,如果发出db.getCollectionNames()的客户端在操作完成前断开连接,MongoDB会使用killOp标记db.getCollectionNames()终止。

Replica Set Member State Restriction副本集成员状态限制

Starting in MongoDB 4.4, to run on a replica set member, listCollections operations require the member to be in PRIMARY or SECONDARY state. 从MongoDB 4.4开始,要在副本集成员上运行,listCollections操作需要该成员处于PRIMARYSECONDARY状态。If the member is in another state, such as STARTUP2, the operation errors.如果成员处于其他状态,例如STARTUP2,则操作将出错。

In previous versions, the operations also run when the member is in STARTUP2. 在以前的版本中,成员处于STARTUP2时也会运行这些操作。The operations wait until the member transitioned to RECOVERING.操作将等待,直到成员转换到RECOVERING

Example实例

The following returns the names of all collections in the records database:以下内容返回records数据库中所有集合的名称:

use records
db.getCollectionNames()

The method returns the names of the collections in an array:该方法返回数组中集合的名称:

[ "employees", "products", "mylogs", "system.indexes" ]