To retrieve particular array elements from distinct MongoDB documents, we can use the $elemMatch operator with the find() method as follows:
db.collection.find({arrayField: {$elemMatch: {field: "value"}}})
where collection
is the name of the MongoDB collection, arrayField
is the name of the field containing the array, field
is the name of the array element field we want to match, and value
is the value we want to find in the array.
For example, if we have a collection called users
containing documents with an array of addresses, we can find users with a specific address city as follows:
db.users.find({addresses: {$elemMatch: {city: "New York"}}})
This will return all users with an address in New York.
Asked: 2022-12-18 11:00:00 +0000
Seen: 12 times
Last updated: Apr 15 '21