计算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()
method显示集合中的所有文档。查询如下:
> 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 }