使用 MongoDB 獲取陣列中不同值的長度


要獲取唯一值,請使用 MongoDB DISTINCT。對於長度,請使用 LENGTH()。讓我們建立一個包含文件的集合 -

> db.demo36.insertOne({"Names":["Chris","Bob"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e17643bcfb11e5c34d898d4")
}
> db.demo36.insertOne({"Names":["Mike","Sam","Carol"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e176449cfb11e5c34d898d5")
}
> db.demo36.insertOne({"Names":["Chris","Bob","David"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e17645bcfb11e5c34d898d6")
}

透過 find() 方法顯示集合中的所有文件 -

> db.demo36.find();

這將產生以下輸出 -

{ "_id" : ObjectId("5e17643bcfb11e5c34d898d4"), "Names" : [ "Chris", "Bob" ] }
{ "_id" : ObjectId("5e176449cfb11e5c34d898d5"), "Names" : [ "Mike", "Sam", "Carol" ] }
{ "_id" : ObjectId("5e17645bcfb11e5c34d898d6"), "Names" : [ "Chris", "Bob", "David" ] }

以下是獲取長度的查詢 -

> db.demo36.distinct('Names').length;

這將產生以下輸出 -

6

更新時間: 02-04-2020

281 次瀏覽

開啟你的 職業生涯

完成課程認證

開始
廣告
© . All rights reserved.