Arrays 无法在聚合中使用$elemMatch
正如标题所示,我无法在聚合中使用Arrays 无法在聚合中使用$elemMatch,arrays,mongodb,aggregate,Arrays,Mongodb,Aggregate,正如标题所示,我无法在聚合中使用$elemMatch。我已经在下面附上了我的代码,我想知道是否有替代代码。我试图匹配并获取数组的所有元素 db.collection.aggregate([ { $match: { s: "A", $or: [ { id: "123" }, { name: "Raj" } ], condition:
$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"
}
]
}
]
}
示例文档应与上述查询匹配。问题:
{
"_id" : ObjectId("5d723e34ef5e6630fde5b71d"),
"id" : 1,
"name" : "Raj",
"category" : 123,
"condition" : [
{
"depend" : [
{
"id" : 1,
"ques" : "test ques"
}
]
},
{
"depend" : [
{
"id" : 2,
"ques" : "test 2nd ques"
}
]
}
]
}
- 示例文档中没有
字段,您正在应用过滤器,即s
s:“a”
和id
都是数字,但与匹配 字符串文字depend.id
数组中没有条件
为123的文档depend.id
db.collection.aggregate([
{
$match:{
$or:[
{
"id":123
},
{
"name":"Raj"
}
],
"condition":{
$elemMatch:{
$and:[
{
"depend.id":1,
"depend.ques": "test ques"
},
{
"depend":{
$size:1
}
}
]
}
}
}
}
]).pretty()
此查询对您的数据非常有效
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"
}
}
])
请发布一份示例文档和预期输出。