MongoDB不同的命令

发布于

在 MongoDB 中,聚合命令在单个集合中查找指定字段的不同值。distinct

它返回一个包含非重复值数组的文档,以及一个包含查询统计信息和查询计划的嵌入文档。

非重复值是那些删除了冗余重复项的值。非重复值是唯一值。例如,如果您有 2 或 3 个具有相同值的文档,则该命令将仅返回一个值。distinct

还有一个方法,它是命令的外壳包装器方法。[db.collection.distinct()](https://database.guide/mongodb-distinct/ "MongoDB distinct()")``distinct

例

假设我们有一个包含以下文档的集合。pets

{ “_id” : 1, “name” : “Wag”, “type” : “Dog”, “weight” : 20 } { “_id” : 2, “name” : “Bark”, “type” : “Dog”, “weight” : 10 } { “_id” : 3, “name” : “Meow”, “type” : “Cat”, “weight” : 7 } { “_id” : 4, “name” : “Scratch”, “type” : “Cat”, “weight” : 8 } { “_id” : 5, “name” : “Bruce”, “type” : “Bat”, “weight” : 3 } { “_id” : 6, “name” : “Fetch”, “type” : “Dog”, “weight” : 17 } { “_id” : 7, “name” : “Jake”, “type” : “Dog”, “weight” : 30 }

我们可以使用该命令返回不同的宠物类型。distinct

该命令接受集合作为第一个字段,接受键作为第二个字段。键是要为其返回非重复值的字段。distinct

db.runCommand ( { distinct: "pets", key: "type" } )

结果:

{ “values” : [ “Bat”, “Cat”, “Dog” ], “ok” : 1 }

在此示例中,即使集合中有四只狗和两只猫,数组也只包含其中一只。该命令删除了重复值。distinct

原始文档只有一个蝙蝠,因此该命令不会更改它 - 没有重复值要重复数据删除。distinct

嵌入式文档

您可以使用点表示法从嵌入字段中获取非重复值

假设我们有一个名为 products 的集合,其中包含以下文档:

{ “_id” : 1, “product” : { “name” : “Shirt”, “color” : “White” }, “sizes” : [ “S”, “M”, “L” ] } { “_id” : 2, “product” : { “name” : “Shirt”, “color” : “Green” }, “sizes” : [ “S”, “M”, “XL” ] } { “_id” : 3, “product” : { “name” : “Shirt”, “color” : “White” }, “sizes” : [ “S”, “M”, “L” ] } { “_id” : 4, “product” : { “name” : “Shorts”, “color” : “Green” }, “sizes” : [ “M”, “XS” ] } { “_id” : 5, “product” : { “name” : “Shorts”, “color” : “Brown” }, “sizes” : [ “S”, “M” ] } { “_id” : 6, “product” : { “name” : “Cap”, “color” : “Purple” }, “sizes” : [ “M” ] } { “_id” : 7, “product” : { “name” : “Shoes”, “color” : “Brown” }, “sizes” : [ “S”, “M”, “L” ] } { “_id” : 8, “product” : { “name” : “Shirt”, “color” : “White” }, “sizes” : [ “M”, “L”, “XL” ] } { “_id” : 9, “product” : { “name” : “Cap”, “color” : “Green” }, “sizes” : [ “M”, “L” ] }

我们可以使用以下查询返回产品名称的不同值。

db.runCommand ( { distinct: "products", key: "product.name" } )

结果:

{ “values” : [ “Cap”, “Shirt”, “Shoes”, “Shorts” ], “ok” : 1 }

我们可以为该领域做同样的事情。color

db.runCommand ( { distinct: "products", key: "product.color" } )

结果:

{ “values” : [ “Brown”, “Green”, “Purple”, “White” ], “ok” : 1 }

从数组中获取非重复值

下面介绍如何使用该命令从上述数组中获取非重复值。distinct

db.runCommand ( { distinct: "products", key: "sizes" } )

结果:

{ “values” : [ “L”, “M”, “S”, “XL”, “XS” ], “ok” : 1 }

与查询一起使用distinct

您可以提供一个查询来指定要从中检索非重复值的文档。为此,请在键后添加查询。

例:

db.runCommand ( { 
    distinct: "products", 
    key: "product.name", 
    query: { "sizes": "S" } 
    } )

结果:

{ “values” : [ “Shirt”, “Shoes”, “Shorts” ], “ok” : 1 }

更多信息

该命令还接受其他字段,例如 、 和(允许您为字符串比较指定特定于语言的规则,例如字母大小写和重音符号的规则)。distinct``comment``readConcern``collation

有关更多信息,请参阅 MongoDB 文档。