Mongodb 计数数组中的子文档总数
我想要数组中的子文档计数,如果可能,不使用Mongodb 计数数组中的子文档总数,mongodb,mongoose,aggregation-framework,Mongodb,Mongoose,Aggregation Framework,我想要数组中的子文档计数,如果可能,不使用$unwind和$group [{ "_id" : ObjectId("5aefead0227bc943df3fedff"), "doc" : [ { "_id" : ObjectId("5af0e877227bc943df401337"), "shared_with" : [ { "user_id"
$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`
}]
您可以先尝试聚合,在doc
上循环,找到shared\u with
数组的值,然后使用聚合对所有shared\u进行计数
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
}
]
您可以使用来统计内部子文档
差不多
db.colname.aggregate([
{"$project":{
"count":{
"$reduce":{
"input":"$doc",
"initialValue":0,
"in":{"$add":["$$value",{"$size":"$$this.shared_with"}]}
}
}
}}
])