db.collection.distinct()

在本页面

Definition

Parameter Type Description
field string 要为其返回不同值的字段。
query document 一个查询,指定要从中检索不同值的文档。
options document 可选的。指定选项的文档。参见Options

db.collection.distinct()方法提供了围绕distinct命令的包装。

Note

结果不得大于最大值BSON size。如果结果超过最大 BSON 大小,请使用聚合管道使用$group运算符检索不同的值,如使用汇总管道检索不同的值中所述。

Options

{ collation: <document> }
Field Type Description
collation document Optional.


指定用于操作的collation
Collation允许用户为字符串比较指定特定于语言的规则,例如字母大写和重音符号的规则。
排序规则选项具有以下语法:
collation: {
locale: <string>,
caseLevel: <boolean>,
caseFirst: <string>,
strength: <int>,
numericOrdering: <boolean>,
alternate: <string>,
maxVariable: <string>,
backwards: <boolean>
}
指定排序规则时,locale字段为必填字段;所有其他排序规则字段都是可选的。有关字段的说明,请参见Collation Document
如果未指定排序规则,但是集合具有默认排序规则(请参见db.createCollection()),则该操作将使用为集合指定的排序规则。
如果没有为集合或操作指定排序规则,则 MongoDB 使用先前版本中使用的简单二进制比较进行字符串比较。
您不能为一个操作指定多个排序规则。例如,您不能为每个字段指定不同的排序规则,或者如果对排序执行查找,则不能对查找使用一种排序规则,而对排序使用另一种排序规则。
3.4 版中的新功能。

Behavior

sharded cluster中,distinct命令可以返回orphaned documents

Array Fields

如果指定的field的值是一个数组,则db.collection.distinct()会将数组的每个元素视为一个单独的值。

例如,如果字段的值为[ 1, [1], 1 ],则db.collection.distinct()1[1]1视为单独的值。

有关示例,请参见返回数组字段的不同值

Index Use

db.collection.distinct()操作可以使用索引。

索引也可以cover db.collection.distinct()个操作。有关由索引覆盖的查询的更多信息,请参见Covered Query

Examples

这些示例使用的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" ] }

返回字段的不同值

下面的示例从inventory集合中的所有文档中返回字段dept的不同值:

db.inventory.distinct( "dept" )

该方法返回以下由不同的dept值组成的数组:

[ "A", "B" ]

返回嵌入式字段的不同值

下面的示例从inventory集合中的所有文档中返回嵌入在item字段中的sku字段的不同值:

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

该方法返回以下由不同的sku值组成的数组:

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

See also

Dot Notation有关访问嵌入式文档中的字段的信息

返回数组字段的不同值

下面的示例从inventory集合中的所有文档中返回字段sizes的不同值:

db.inventory.distinct( "sizes" )

该方法返回以下由不同的sizes值组成的数组:

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

有关distinct()和数组字段的信息,请参见Behavior部分。

以不同的方式指定查询

下面的示例从dept等于"A"的文档中返回嵌入在item字段中的字段sku的不同值:

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

该方法返回以下由不同的sku值组成的数组:

[ "111", "333" ]

指定排序规则

3.4 版的新功能。

Collation允许用户为字符串比较指定特定于语言的规则,例如字母大写和重音符号的规则。

集合myColl具有以下文档:

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

以下聚合操作包括Collation选项:

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

有关整理字段的说明,请参见Collation Document

首页