ऐरे में आइटम्स की संख्या गिनने के लिए, आप $size ऑपरेटर का उपयोग कर सकते हैं। सिंटैक्स इस प्रकार है:
db.yourCollectionName.aggregate({$project:{anyFieldName:{$size:"$yourArrayName"}}}).pretty();
उपरोक्त सिंटैक्स को समझने के लिए, आइए डॉक्यूमेंट के साथ एक कलेक्शन बनाएं। डॉक्यूमेंट के साथ कलेक्शन बनाने की क्वेरी इस प्रकार है:
>db.getSizeOfArray.insertOne({"StudentId":1,"StudentName":"Larry","StudentMarks":[87,34,56,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"}}}).pretty();
निम्नलिखित आउटपुट है:
{ "_id" : ObjectId("5c6ebc536fd07954a4890680"), "NumberOfItemsInArray" : 6 }
{ "_id" : ObjectId("5c6ebc6b6fd07954a4890681"), "NumberOfItemsInArray" : 3 }
{ "_id" : ObjectId("5c6ebc7a6fd07954a4890682"), "NumberOfItemsInArray" : 2 }