正如标题所示,我无法在聚合内使用$elemMatch
。我已在下面附加了我的代码,我想知道是否有替代此代码的代码。我正在尝试匹配并获取数组的所有元素。
db.collection.aggregate([
{
$match: {
s: "A",
$or: [
{
id: "123"
},
{
name: "Raj"
}
],
condition: {
$elemMatch: {
$and: [
{
"depend.id": "123",
"depend.ques": "test ques"
},
{
depend: {
$size: 1
}
}
]
}
}
}
},
{
$lookup: {
from: "categories",
localField: "category",
foreignField: "_id",
as: "category"
}
},
{
$unwind: "$category"
}
])
示例文档:
{
"_id" : ObjectId("5d723e34ef5e6630fde5b71d"),
"id" : 1,
"name" : "Raj",
"category" : 123,
"condition" : [
{
"depend" : [
{
"id" : 1,
"ques" : "test ques"
}
]
},
{
"depend" : [
{
"id" : 2,
"ques" : "test 2nd ques"
}
]
}
]
}
示例文档应与以上查询匹配。
答案 0 :(得分:1)
问题:
s
字段,而您正在s: "A"
中应用过滤器id
和depend.id
均为数字,但与
字符串文字condition
数组中没有文档,depend.id
为123 请参考以下查询:
db.collection.aggregate([
{
$match:{
$or:[
{
"id":123
},
{
"name":"Raj"
}
],
"condition":{
$elemMatch:{
$and:[
{
"depend.id":1,
"depend.ques": "test ques"
},
{
"depend":{
$size:1
}
}
]
}
}
}
}
]).pretty()
答案 1 :(得分:0)
此查询非常适合您的数据。
db.getCollection('stackans').aggregate([
{
$match: {
$or: [
{
id: 1
},
{
name: "Raj"
}
],
condition: {
$elemMatch: {
$and: [
{
"depend.id": 1,
"depend.ques": "test ques"
},
{
depend: {
$size: 1
}
}
]
}
}
}
} ,{
$lookup: {
from: "categories",
localField: "category",
foreignField: "_id",
as: "category"
}
}
])