我正在尝试使用elemMatch基于嵌套在数组和第二个数组中的值查询集合和过滤器。
{
"email": "user1@email.com",
"project" [ {
projectId: ObjectId("123"),
preference: [
{"name": "name1", "value": true},
{"name": "name2", "value": false}
]
},
{
projectId: ObjectId("456"),
preference: [
{"name": "name1", "value": true},
{"name": "name2", "value": true}
]
}
]
},
{
"email": "user2@email.com",
"project" [ {
projectId: ObjectId("123"),
preference: [
{"name": "name1", "value": false},
{"name": "name2", "value": true}
]
},
{
projectId: ObjectId("456"),
preference: [
{"name": "name1", "value": true},
{"name": "name2", "value": true}
]
}
]
}
我尝试了几种不同的变体,将以下两个查询合并为一个,以尝试实现我的返回目标。
{email:“ user1@email.com”}
db.user.find({"project":{"$elemMatch":{"projectId":ObjectId("123")}}}, {email: 1})
db.user.find({"project.preference":{"$elemMatch":{"$and":[{"name":"name1"}, {"value": true}]}}}, {email: 1})
答案 0 :(得分:0)
您可以使用$unwind简化查询多层嵌套数组的操作,请尝试:
db.user.aggregate([
{ $unwind: "$project" },
{ $match: { "project.projectId": "123" } },
{ $unwind: "$project.preference" },
{ $match: { "project.preference.name": "name1", "project.preference.value": true } },
{ $project: { _id: 0, email: 1 } }
])