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.
-
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.