배열의 항목 수를 계산하려면 $size 연산자를 사용할 수 있습니다. 구문은 다음과 같습니다.
db.yourCollectionName.aggregate({$project:{anyFieldName:{$size:"$yourArrayName"}}}).prett
y(); 위의 구문을 이해하기 위해 document를 사용하여 컬렉션을 생성해 보겠습니다. 문서로 컬렉션을 생성하는 쿼리는 다음과 같습니다.
>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 }