db.collection.distinct()

On this page本页内容

Definition定义

db.collection.distinct(field, query, options)

mongo Shell Method方法

This page documents the mongo shell method, and does not refer to the MongoDB Node.js driver (or any other driver) method. 本页记录了mongo shell方法,未提及MongoDB Nodejs驱动程序(或任何其他驱动程序)方法。For corresponding MongoDB driver API, refer to your specific MongoDB driver documentation instead.有关相应的MongoDB驱动程序API,请参阅特定的MongoDB驱动程序文档

Finds the distinct values for a specified field across a single collection or view and returns the results in an array.在单个集合或视图中查找指定字段的不同值,并在数组中返回结果。

Parameter参数Type类型Description描述
field string The field for which to return distinct values.要为其返回不同值的字段。
query document文件 A query that specifies the documents from which to retrieve the distinct values.指定要从中检索不同值的文档的查询。
options document Optional.可选。A document that specifies the options. 指定选项的文档。See Options.请参阅选项

The db.collection.distinct() method provides a wrapper around the distinct command.db.collection.distinct()方法为distinct命令提供包装。

Note

Results must not be larger than the maximum BSON size. 结果不得大于最大BSON大小If your results exceed the maximum BSON size, use the aggregation pipeline to retrieve distinct values using the $group operator, as described in Retrieve Distinct Values with the Aggregation Pipeline.如果结果超过最大BSON大小,请使用聚合管道使用$group运算符检索不同的值,如使用聚合管道检索不同的值中所述。

Options选项

{ collation: <document> }
Field字段Type类型Description描述
collation document

Optional.可选。

Specifies the collation to use for the operation.指定要用于该操作的排序规则

Collation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks.排序规则允许用户为字符串比较指定特定于语言的规则,例如字母大小写和重音符号的规则。

The collation option has the following syntax:collation选项语法如下所示:

collation: {
   locale: <string>,
   caseLevel: <boolean>,
   caseFirst: <string>,
   strength: <int>,
   numericOrdering: <boolean>,
   alternate: <string>,
   maxVariable: <string>,
   backwards: <boolean>
}

When specifying collation, the locale field is mandatory; all other collation fields are optional. 指定排序规则时,locale字段是必需的;所有其他排序规则字段都是可选的。For descriptions of the fields, see Collation Document.有关这些字段的描述,请参阅排序规则文档。

If the collation is unspecified but the collection has a default collation (see db.createCollection()), the operation uses the collation specified for the collection.如果未指定排序规则,但集合具有默认排序规则(请参见db.createCollection()),则操作将使用为集合指定的排序规则。

If no collation is specified for the collection or for the operations, MongoDB uses the simple binary comparison used in prior versions for string comparisons.如果没有为集合或操作指定排序规则,MongoDB将使用以前版本中用于字符串比较的简单二进制比较。

You cannot specify multiple collations for an operation. 不能为一个操作指定多个排序规则。For example, you cannot specify different collations per field, or if performing a find with a sort, you cannot use one collation for the find and another for the sort.例如,不能为每个字段指定不同的排序规则,或者如果使用排序执行查找,则不能对查找使用一种排序规则,对排序使用另一种排序规则。

New in version 3.4.版本3.4中的新功能。

Behavior行为

In a sharded cluster, the distinct command may return orphaned documents.分片集群中,distinct命令可能返回孤立文档

Array Fields数组字段

If the value of the specified field is an array, db.collection.distinct() considers each element of the array as a separate value.如果指定field的值是数组,则db.collection.distinct()将数组的每个元素视为一个单独的值。

For instance, if a field has as its value [ 1, [1], 1 ], then db.collection.distinct() considers 1, [1], and 1 as separate values.

For an example, see Return Distinct Values for an Array Field.有关示例,请参阅返回数组字段的不同值

Index Use索引使用

When possible, db.collection.distinct() operations can use indexes.如果可能的话,db.collection.distinct()操作可以使用索引。

Indexes can also cover db.collection.distinct() operations. 索引还可以覆盖db.collection.distinct()操作。See Covered Query for more information on queries covered by indexes.有关索引覆盖的查询的更多信息,请参阅覆盖的查询

Transactions事务

To perform a distinct operation within a transaction:要在事务中执行不同的操作:

  • For unsharded collections, you can use the db.collection.distinct() method/the distinct command as well as the aggregation pipeline with the $group stage.对于未分级的集合,可以使用db.collection.distinct()方法/distinct命令以及带有$group阶段的聚合管道。
  • For sharded collections, you cannot use the db.collection.distinct() method or the distinct command.对于分片集合,不能使用db.collection.distinct()方法或distinct命令。

    To find the distinct values for a sharded collection, use the aggregation pipeline with the $group stage instead. 要查找分片集合的不同值,请将聚合管道与$group阶段一起使用。See Distinct Operation for details.有关详细信息,请参阅Distinct操作

Important重要的

In most cases, multi-document transaction incurs a greater performance cost over single document writes, and the availability of multi-document transactions should not be a replacement for effective schema design. 在大多数情况下,与单文档写入相比,多文档事务会带来更大的性能成本,而多文档事务的可用性不应取代有效的模式设计。For many scenarios, the denormalized data model (embedded documents and arrays) will continue to be optimal for your data and use cases. 对于许多场景,非规范化数据模型(嵌入式文档和数组)将继续适合您的数据和用例。That is, for many scenarios, modeling your data appropriately will minimize the need for multi-document transactions.也就是说,对于许多场景,适当地建模数据将最大限度地减少对多文档事务的需求。

For additional transactions usage considerations (such as runtime limit and oplog size limit), see also Production Considerations.有关其他事务使用注意事项(如运行时限制和oplog大小限制),请参阅生产注意事项

Client Disconnection客户端断开

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

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

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

In previous versions, the operations can also be run when the member is in STARTUP2. 在以前的版本中,当成员在STARTUP2中时,也可以运行这些操作。However, the operations wait until the member transitions to RECOVERING.但是,这些操作将等待成员转换到恢复状态

Examples示例

The examples use the inventory collection that contains the following documents:这些示例使用包含以下文档的inventory集合:

{ "_id": 1, "dept": "A", "item": { "sku": "111", "color": "red" }, "sizes": [ "S", "M" ] }
{ "_id": 2, "dept": "A", "item": { "sku": "111", "color": "blue" }, "sizes": [ "M", "L" ] }
{ "_id": 3, "dept": "B", "item": { "sku": "222", "color": "blue" }, "sizes": "S" }
{ "_id": 4, "dept": "A", "item": { "sku": "333", "color": "black" }, "sizes": [ "S" ] }

Return Distinct Values for a Field为字段返回不同的值

The following example returns the distinct values for the field dept from all documents in the inventory collection:以下示例从inventory集合中的所有文档返回字段dept的不同值:

db.inventory.distinct( "dept" )

The method returns the following array of distinct dept values:该方法返回以下不同dept值的数组:

[ "A", "B" ]

Return Distinct Values for an Embedded Field为嵌入字段返回不同的值

The following example returns the distinct values for the field sku, embedded in the item field, from all documents in the inventory collection:以下示例返回库存集合中所有文档中嵌入在item字段中的字段sku的不同值:

db.inventory.distinct( "item.sku" )

The method returns the following array of distinct sku values:该方法返回以下不同sku值的数组:

[ "111", "222", "333" ]

See also参阅

Dot Notation for information on accessing fields within embedded documents用于访问嵌入文档中字段的信息的点符号

Return Distinct Values for an Array Field为数组字段返回不同的值

The following example returns the distinct values for the field sizes from all documents in the inventory collection:以下示例返回inventory集合中所有文档的字段size的不同值:

db.inventory.distinct( "sizes" )

The method returns the following array of distinct sizes values:该方法返回以下不同sizes值的数组:

[ "M", "S", "L" ]

For information on distinct() and array fields, see the Behavior section.有关distinct()和数组字段的信息,请参阅行为部分。

Specify Query with distinct使用distinct指定查询

The following example returns the distinct values for the field sku, embedded in the item field, from the documents whose dept is equal to "A":以下示例从dept等于"A"的文档中返回项目字段中嵌入的字段sku的不同值:

db.inventory.distinct( "item.sku", { dept: "A" } )

The method returns the following array of distinct sku values:该方法返回以下不同sku值的数组:

[ "111", "333" ]

Specify a Collation指定排序规则

New in version 3.4.版本3.4中的新功能。

Collation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks.排序规则允许用户为字符串比较指定特定于语言的规则,例如字母大小写和重音符号的规则。

A collection myColl has the following documents:myColl集合包含以下文档:

{ _id: 1, category: "café", status: "A" }
{ _id: 2, category: "cafe", status: "a" }
{ _id: 3, category: "cafE", status: "a" }

The following aggregation operation includes the Collation option:以下聚合操作包括排序规则选项:

db.myColl.distinct( "category", {}, { collation: { locale: "fr", strength: 1 } } )

For descriptions on the collation fields, see Collation Document.有关排序规则字段的说明,请参阅排序规则文档