On this page
db.collection.distinct()
在本页面
Definition
db.collection.
distinct
(* field , query , options *)- 在单个集合或视图中查找指定字段的不同值,并将结果返回到数组中。
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。