Fetch only matching nested Array document only

I want to fetch exactly matching array nested document only which tag_name is “Testnew”.

{
“_id”: {
“$oid”: “63c142fe7d89cf0a303e70f9”
},
“organization_id”: {
“$numberLong”: “200020”
},
“tags”: [
{
“tag_name”: “Testnew”,
“status”: true,
},
{
“tag_name”: “Testnew”,
“status”: true,
} ,
{
“tag_name”: “Test”,
“status”: true,
}
],
}

{ “tags” : { “$elemMatch” : { “tag_name” : “Testnew”, “status” : true}}}
it returns full document with all nested array those are also not matched.

My expect result is:
“tags”: [
{
“tag_name”: “Testnew”,
“status”: true,
},
{
“tag_name”: “Testnew”,
“status”: true,
}

Please share any query so that I can find exact matches data,

Please read Formatting code and log snippets in posts and update your sample documents, code and expected result.

If you were only interested in the first element you could use a projection that repeats your $elemMatch

If you are interested in all elements that match, which your expect result shows, it is a little bit more complicated. You need a $filter projection such as:

{ "tags" : { "$filter" : {
    "input" : "$tags" ,
    "cond" : {
        "$and" : [
            { "$eq" : [ "$$this.tag_name" , "Testnew" ] } ,
            { "$eq" : [ "$$this.status" , true ] }
        ]
    }
} } }
1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.