在 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 }
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP