Searching in Array with double conditions

I am struggling a bit on how to do this via search instead of a “regular” query. My goal is to find a record where there is an matching element in an array based on 2 properties.

In “normal” query it would basically be(ignoring detils):
$match: {
Fields: {
$elemMatch: {
SomeID: ObjectId(
“62b4d1d79cbf0bed0fbe35ca”
),
Value: “test”
}
}
}

I want to find the record which has an element with a value = test but ALSO and id(or whatever) = xxxx

In c# LINQ terms: someArray.Find(x => x.ID == XXX && value == YYY)

I cannot seem to get this to work in Atlas Search when the value == YYY is the “non exact” match I am searching on. Of course I can find the record when I just search for the YYYY, but I cannot figure out how to use a “Should” with a “MUST” and force it to match the SAME element.

Example:
[
{
ID = 123,
Value = ABC
},
{
ID = 456,
Value = XXX
}
]

I want to only find records which have a “X” in the value but ONLY when the ID is also “123”. When I try to combine a MUST/SHOULD in a compound I always get the record above because MUST 123 us true(first item in the array) and SHOULD “X” is true(second item in the array) and so I get a true.

Short Version: It works in slower non-search mode I just cannot figure out the syntax for Atlas Search mode.

Any ideas?

A little tricky, but embeddedDocuments is how to group nested documents together so that they can be matched like elemMatch does. Here’s an Atlas Search Playground example that gets close to what you’re looking for.

Be sure to heed the recommendations in the nested documents section of the data modeling for search document. You may be best served by modeling your data differently for this need.

1 Like