Reputation: 790
As the title suggests I am unable to use $elemMatch
inside aggregate. I have attached my code below, and I would like to know if there is an alternative to this code. I'm trying to match and get all the elements of an array.
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"
}
])
Sample document:
{
"_id" : ObjectId("5d723e34ef5e6630fde5b71d"),
"id" : 1,
"name" : "Raj",
"category" : 123,
"condition" : [
{
"depend" : [
{
"id" : 1,
"ques" : "test ques"
}
]
},
{
"depend" : [
{
"id" : 2,
"ques" : "test 2nd ques"
}
]
}
]
}
The sample document should be matched with the above query.
Upvotes: 1
Views: 3777
Reputation: 5590
This Query is perfectly working on your data.
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"
}
}
])
Upvotes: 1
Reputation: 3010
Issues:
s
field in the sample document and you are applying a filter on in i.e. s: "A"
id
and depend.id
are numeric but are matched with
string literalscondition
array with depend.id
as 123Please refer the following query:
db.collection.aggregate([
{
$match:{
$or:[
{
"id":123
},
{
"name":"Raj"
}
],
"condition":{
$elemMatch:{
$and:[
{
"depend.id":1,
"depend.ques": "test ques"
},
{
"depend":{
$size:1
}
}
]
}
}
}
}
]).pretty()
Upvotes: 2