我对mongodb的收集记录
{
"_id" : ObjectId("5ba60b805f13dc37a5377302"),
"clientID" : "5ba49a5b58db5fb63b282565",
"propertyID" : "77f3d86a9842afa8ee7a64f3bf958ef4",
"emod" : [
{
"audience" : "Mobile",
"emodID" : "5ba5e0f47b07641eeebfad37",
},
{
"audience" : "Laptop",
"emodID" : "5ba5e0f47b07641eeebfad37",
},
{
"audience" : "Games",
"emodID" : "5ba5e0f47b07641eeebfad37"
}]
}
查找记录查询
var audienceList = ["Mobile","Laptop"];
predictionCollection.findOne({
"clientID": '5ba49a5b58db5fb63b282565',
}, {
emod: {
$elemMatch: {
'audience': {"$in":audienceList}
}
},
}).exec(function (err, predictionData) {
预测数据的输出
emod: [ { audience: 'Mobile', emodID: '5ba5e0f47b07641eeebfad37' } ] }
但是我需要输出
emod: [ { audience: 'Mobile', emodID:'5ba5e0f47b07641eeebfad37' },
{ audience: 'Laptop', emodID:'5ba5e0f47b07641eeebfad37' }
] }
});
我正在使用mongo聚集
我还使用了$ elementMatch和$ in来匹配所有数组
答案 0 :(得分:0)
$elemMatch
仅返回数组中的第一个元素。
因此,您需要将$filter
与$in
聚合运算符一起使用,以检索所有符合条件的元素
db.collection.aggregate([
{ "$match": { "clientID": "5ba49a5b58db5fb63b282565" }},
{ "$project": {
"emod": {
"$filter": {
"input": "$emod",
"as": "em",
"cond": { "$in": ["$$em.audience", ["Mobile", "Laptop"]] }
}
}
}}
])