Mongodb 基于条件查找和计数mongo数组中的一致性
假设我有一个文档集,类似于:Mongodb 基于条件查找和计数mongo数组中的一致性,mongodb,aggregation-framework,Mongodb,Aggregation Framework,假设我有一个文档集,类似于: { _id :ObjectId("45645645gdfgdfgdf"), article:"article one", topic:["config","develop","show"], keys[ {subject:"one",object"abc"}, {subject:"one",object"def"}, {subject:"two",object"ghi"}, {subject:"four",object"jkl"},
{
_id :ObjectId("45645645gdfgdfgdf"),
article:"article one",
topic:["config","develop","show"],
keys[
{subject:"one",object"abc"},
{subject:"one",object"def"},
{subject:"two",object"ghi"},
{subject:"four",object"jkl"},
{subject:"four",object"mnl"},
{subject:"four",object"mnl"},
]
},
{
_id :ObjectId("45645645gdfgdfgdf"),
article:"article two",
topic:["config","installing"],
keys[
{subject:"one",object"abc"},
{subject:"one",object"def"},
{subject:"two",object"ghi"},
{subject:"two",object"jkl"},
]
},
{
_id :ObjectId("45645645gdfgdfgdf"),
article:"article three",
topic:["config","installing"],
keys[
{subject:"five",object"abc"},
{subject:"five",object"def"},
{subject:"two",object"ghi"},
{subject:"two",object"jkl"},
]
}
我想根据一个条件计算数组中的每个主题,并按主题过滤,例如,假设我按主题搜索:“config”和主题:[“one”,“four”]结果需要
{article :"article one", sum:5},{article :"article two", sum:2}
thks提前您可以使用下面的聚合
db.colname.aggregate([
{"$match":{"topic":"config","subject":{"$in":["one","four"]}}},
{"$project":{
"article":1,
"sum":{
"$size":{
"$filter":{
"input":"$keys",
"cond":{"$in":["$$this.subject",["one","four"]]}
}
}
}
}}
])
谢谢,这段代码帮助我理解了mongo的查询思想