要获取唯一值并忽略重复项,请在MongoDB中使用distinct()。different()在单个集合中查找指定字段的不同值,并将结果返回到数组中。
让我们创建一个包含文档的集合-
> 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" ]