Computer >> Máy Tính >  >> Lập trình >> MongoDB

Đếm số mục trong một mảng trong MongoDB?

Để đếm số lượng mục trong một mảng, bạn có thể sử dụng toán tử $ size. Cú pháp như sau:

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

Để hiểu cú pháp trên, chúng ta hãy tạo một bộ sưu tập với tài liệu. Truy vấn để tạo một bộ sưu tập với tài liệu như sau:

>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")
}

Bây giờ bạn có thể hiển thị tất cả các tài liệu từ một bộ sưu tập với sự trợ giúp của phương thức find (). Truy vấn như sau:

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

Sau đây là kết quả:

{
   "_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
   ]
}

Sau đây là truy vấn để đếm số lượng mục trong một mảng:

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

Sau đây là kết quả:

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