如何在MongoDB中仅返回唯一值(无重复)?
您可以distinct()
用来仅返回唯一值。语法如下-
db.yourCollectionName.distinct("yourFieldName");
为了理解这个概念,让我们用文档创建一个集合。使用文档创建集合的查询如下-
> db.returnOnlyUniqueValuesDemo.insertOne({"CusomerName":"Larry","CustomerAge":23}); { "acknowledged" : true, "insertedId" : ObjectId("5c8ed7262f684a30fbdfd580") } > db.returnOnlyUniqueValuesDemo.insertOne({"CusomerName":"Mike","CustomerAge":21}); { "acknowledged" : true, "insertedId" : ObjectId("5c8ed72d2f684a30fbdfd581") } > db.returnOnlyUniqueValuesDemo.insertOne({"CusomerName":"Sam","CustomerAge":21}); { "acknowledged" : true, "insertedId" : ObjectId("5c8ed7322f684a30fbdfd582") } > db.returnOnlyUniqueValuesDemo.insertOne({"CusomerName":"Carol","CustomerAge":25}); { "acknowledged" : true, "insertedId" : ObjectId("5c8ed73a2f684a30fbdfd583") } > db.returnOnlyUniqueValuesDemo.insertOne({"CusomerName":"David","CustomerAge":22}); { "acknowledged" : true, "insertedId" : ObjectId("5c8ed74a2f684a30fbdfd584") } > db.returnOnlyUniqueValuesDemo.insertOne({"CusomerName":"Chris","CustomerAge":23}); { "acknowledged" : true, "insertedId" : ObjectId("5c8ed7582f684a30fbdfd585") }
在find()
method的帮助下显示集合中的所有文档。查询如下-
> db.returnOnlyUniqueValuesDemo.find().pretty();
以下是输出-
{ "_id" : ObjectId("5c8ed7262f684a30fbdfd580"), "CusomerName" : "Larry", "CustomerAge" : 23 } { "_id" : ObjectId("5c8ed72d2f684a30fbdfd581"), "CusomerName" : "Mike", "CustomerAge" : 21 } { "_id" : ObjectId("5c8ed7322f684a30fbdfd582"), "CusomerName" : "Sam", "CustomerAge" : 21 } { "_id" : ObjectId("5c8ed73a2f684a30fbdfd583"), "CusomerName" : "Carol", "CustomerAge" : 25 } { "_id" : ObjectId("5c8ed74a2f684a30fbdfd584"), "CusomerName" : "David", "CustomerAge" : 22 } { "_id" : ObjectId("5c8ed7582f684a30fbdfd585"), "CusomerName" : "Chris", "CustomerAge" : 23 }
这是只返回唯一值的查询-
> db.returnOnlyUniqueValuesDemo.distinct("CustomerAge");
以下是输出:
[ 23, 21, 25, 22 ]