Return results from within arrays
I have a document that looks like this:
{
shoppingList: [ { name: "red hat"}, { name: "green shoes"} ]
}
I would like to query $search for "green" and return {name: "green shoes"} instead of returning the entire document.

-
Justin commented
Would this also fix sorting on embedded properties? I have used the filter in a projection to sort of make this work for hard filter values. But as pointed out this is not possible for things like autocomplete and text with fuzzy and such.
On top of those issues I think this may solve sorting if I'm understanding correctly. Today if I sort on an embedded property it will sort all of the parents based on all of their embedded documents and not just the embedded documents that match. I don't think this sort can be moved as it's needed to create the next token for pagination.
Would this feature fix this issue?
-
Krishnamoorthy commented
I have almost similar requirement.
my document looks like this
{
"_id": "123",
"name": "abc",
"programmingLanguage": [
{
"id": 1,
"language": "Rust"
},
{
"id": 2,
"language": "Python"
}
]
}Need to match only "Python" and return the result like this
{
"_id": "123",
"name": "abc",
"programmingLanguage": [
{
"id": 2,
"language": "Python"
}
]
} -
AdminAmy (Admin, MongoDB) commented
To return only matching sub-documents within arrays, you can use an equivalent $filter expression in the $project stage of your pipeline. See Playground example: https://search-playground.mongodb.com/tools/code-playground/snapshots/667adca6fef99fff9972a251
This works well for $search expressions that have equivalent $filter expressions (e.g. equals, in, range), however, some query operators like autocomplete or text may need to be approximated with $regexMatch or similar. For more information, read the docs: https://www.mongodb.com/docs/atlas/atlas-search/embedded-document/#query-for-matching-embedded-documents-only
(Edited by admin) -
Ethan commented
For those reading, there is an operator to search within the objects of arrays, however that will merely tell you that the string exists within the array of objects. It's called embeddedDocuments. To discover which object within the array matches a query, other methods like a materialized view may be needed.
-
Maria Concordia commented
I also need to be able to search within an array of documents and retrieve one document out of the array that matches my query params.