在 MongoDB 中計算陣列中的項數?


要計算陣列中的項數,你可以使用 $size 運算子。語法如下

db.yourCollectionName.aggregate({$project:{anyFieldName:{$size:"$yourArrayName"}}}).prett
y();

要理解上面的語法,讓我們建立一個帶文件的集合。建立帶有文件的集合的查詢如下

>db.getSizeOfArray.insertOne({"StudentId":1,"StudentName":"Larry","StudentMarks":[87,34,5
6,77,89,90]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c6ebc536fd07954a4890680")
}
>db.getSizeOfArray.insertOne({"StudentId":2,"StudentName":"Sam","StudentMarks":[90,76,56
]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c6ebc6b6fd07954a4890681")
}
>db.getSizeOfArray.insertOne({"StudentId":3,"StudentName":"Carol","StudentMarks":[90,76]})
;
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c6ebc7a6fd07954a4890682")
}

現在你可以使用 find() 方法顯示集合中的所有文件。查詢如下

> db.getSizeOfArray.find().pretty();

以下是輸出

{
   "_id" : ObjectId("5c6ebc536fd07954a4890680"),
   "StudentId" : 1,
   "StudentName" : "Larry",
   "StudentMarks" : [
      87,
      34,
      56,
      77,
      89,
      90
   ]
}
{
   "_id" : ObjectId("5c6ebc6b6fd07954a4890681"),
   "StudentId" : 2,
   "StudentName" : "Sam",
   "StudentMarks" : [
      90,
      76,
      56
   ]
}
{
   "_id" : ObjectId("5c6ebc7a6fd07954a4890682"),
   "StudentId" : 3,
   "StudentName" : "Carol",
   "StudentMarks" : [
      90,
      76
   ]
}

以下是計算陣列中項數的查詢

>db.getSizeOfArray.aggregate({$project:{NumberOfItemsInArray:{$size:"$StudentMarks"}}}).p
retty();

以下是輸出

{ "_id" : ObjectId("5c6ebc536fd07954a4890680"), "NumberOfItemsInArray" : 6 }
{ "_id" : ObjectId("5c6ebc6b6fd07954a4890681"), "NumberOfItemsInArray" : 3 }
{ "_id" : ObjectId("5c6ebc7a6fd07954a4890682"), "NumberOfItemsInArray" : 2 }

更新時間: 2019 年 7 月 30 日

5K+ 瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.