如果可能,我希望不使用$unwind
和$group
来计数数组中的子文档。
[{
"_id" : ObjectId("5aefead0227bc943df3fedff"),
"doc" : [
{
"_id" : ObjectId("5af0e877227bc943df401337"),
"shared_with" : [
{
"user_id" : ObjectId("5ad5e57b473e2606e0d443c3"),
"_id" : ObjectId("5af0e877227bc943df401339")
},
{
"user_id" : ObjectId("5adbf029b2da8e380b9321b6"),
"_id" : ObjectId("5af0e877227bc943df401338")
}
]
},
{
"_id" : ObjectId("5b4d856702d7f52974aab962"),
"shared_with" : [
{
"user_id" : ObjectId("5ac7083ce56c9d304f2fa533"),
"_id" : ObjectId("5b4d856702d7f52974aab963")
}
]
}
]
}]
上面是我查找后得到的结果,我想计算包含文档的数组('doc')中的子文档('shared_with')的总数,
所以我想要的输出如下,
[{
"_id" : ObjectId("5aefead0227bc943df3fedff"),
"count":3`enter code here`
}]
答案 0 :(得分:2)
您可以先尝试进行$map
聚合,以遍历doc
并找到shared_with
数组的$size
,然后将所有shared_with
用{ {3}}聚合
db.collection.aggregate([
{ "$project": {
"doc": {
"$map": {
"input": "$doc",
"as": "do",
"in": {
"_id": "$$do._id",
"count": { "$size": "$$do.shared_with" }
}
}
}
}},
{ "$project": {
"count": { "$sum": "$doc.count" }
}}
])
输出
[
{
"_id": ObjectId("5aefead0227bc943df3fedff"),
"count": 3
}
]
答案 1 :(得分:1)
您可以使用$reduce
来计数内部子文档。
类似
db.colname.aggregate([
{"$project":{
"count":{
"$reduce":{
"input":"$doc",
"initialValue":0,
"in":{"$add":["$$value",{"$size":"$$this.shared_with"}]}
}
}
}}
])