如何从 MongoDB 集合中获取唯一值?


若要获取唯一值并忽略重复项,请在 MongoDB 中使用 distinct()。distinct() 会找到整个单一集合中特定字段的唯一值,并以数组形式返回结果。

让我们创建一个包含文档的集合 −

> db.demo704.insertOne({"LanguageCode":"hi"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea6ee18551299a9f98c93bd")
}
> db.demo704.insertOne({"LanguageCode":"en"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea6ee1e551299a9f98c93be")
}
> db.demo704.insertOne({"LanguageCode":"hi"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea6ee20551299a9f98c93bf")
}
> db.demo704.insertOne({"LanguageCode":"eo"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea6ee2c551299a9f98c93c0")
}
> db.demo704.insertOne({"LanguageCode":"eu"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea6ee2f551299a9f98c93c1")
}
> db.demo704.insertOne({"LanguageCode":"fo"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea6ee35551299a9f98c93c2")
}
> db.demo704.insertOne({"LanguageCode":"fo"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea6ee37551299a9f98c93c3")
}

借助 find() 方法显示某个集合中的所有文档 −

> db.demo704.find();

这会生成以下输出 −

{ "_id" : ObjectId("5ea6ee18551299a9f98c93bd"), "LanguageCode" : "hi" }
{ "_id" : ObjectId("5ea6ee1e551299a9f98c93be"), "LanguageCode" : "en" }
{ "_id" : ObjectId("5ea6ee20551299a9f98c93bf"), "LanguageCode" : "hi" }
{ "_id" : ObjectId("5ea6ee2c551299a9f98c93c0"), "LanguageCode" : "eo" }
{ "_id" : ObjectId("5ea6ee2f551299a9f98c93c1"), "LanguageCode" : "eu" }
{ "_id" : ObjectId("5ea6ee35551299a9f98c93c2"), "LanguageCode" : "fo" }
{ "_id" : ObjectId("5ea6ee37551299a9f98c93c3"), "LanguageCode" : "fo" }

以下查询可以获取唯一值,并在数组中显示结果 −

> db.demo704.distinct("LanguageCode");

这会生成以下输出 −

[ "hi", "en", "eo", "eu", "fo" ]

更新于: 14-5-2020

17K+ 浏览量

Kickstart Your Career

完成教程获得认证

开始
广告