有Post收集数据。
{"_id" : 1
,"subject" : "post1"
,"usersLiking": [
{"user_id" : "user_id_01", "username" : "user01"}
{"user_id" : "user_id_02", "username" : "user02"}
]
,"usersDisliking": [
{"user_id" : "user_id_03", "username" : "user03"}
{"user_id" : "user_id_04", "username" : "user04"}
{"user_id" : "user_id_05", "username" : "user05"}
]
}
,{"_id" : 2
,"subject" : "post2"
,"usersLiking": [
{"user_id" : "user_id_01", "username" : "user01"}
]
,"usersDisliking": [
{"user_id" : "user_id_03", "username" : "user03"}
{"user_id" : "user_id_04", "username" : "user04"}
]
}
我希望输出如下。
{"_id" : 1, "usersLikingCount" : 2, "usersDislikingCount" : 3}
{"_id" : 2, "usersLikingCount" : 1, "usersDislikingCount" : 2}
这对我来说太复杂了。我想得到多个嵌入文档的数量。查询是什么? 感谢。
答案 0 :(得分:0)
试试这个
db.collectionName.aggregate({"$project":{"usersLikingCount":{"$size":"$usersLiking"},"usersDislikingCount":{"$size":"$usersDisliking"}}})