在MongoDB中返回不同值的3种方法

发布于

非重复值是删除了冗余重复项的值。换句话说,非重复值是唯一值。

在MongoDB中,有几种方法可以在查询中返回不同的值。本文介绍了在 mongo shell 中返回不同值的 3 种方法。

示例数据

此页上的示例使用以下集合,称为: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()

在MongoDB中,该方法在单个集合或视图中查找指定字段的不同值,并在数组中返回结果。db.collection.distinct()

例:

db.pets.distinct( "type" )

结果:

[ “Bat”, “Cat”, “Dog” ]

这三个值是上述文档中字段的不同值。type

该部件仅命名要从中返回非重复值的集合。pets

该方法是命令的外壳包装器方法(如下)。db.collection.distinct()``distinct

命令distinct

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

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

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

结果:

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

我们可以看到返回相同的非重复值,只是这次它们位于还包含其他信息的文档中。

聚合运算符$group

根据需要,还可以使用聚合运算符返回非重复值。$group

例:

db.pets.aggregate( [ { $group : { _id : "$type" } } ] )

结果:

{ “_id” : “Cat” } { “_id” : “Bat” } { “_id” : “Dog” }

在这种情况下,非重复值在单独的文档中返回。

如果您预计结果很大,则此方法可能很有用。如果您的结果大于最大 BSON 大小(撰写本文时为 16 MB),您可能需要使用此方法。