Ask Your Question
0

What is the method for retrieving particular array elements from distinct MongoDb documents?

asked 2022-12-18 11:00:00 +0000

pufferfish gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2021-04-15 14:00:00 +0000

huitzilopochtli gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-12-18 11:00:00 +0000

Seen: 11 times

Last updated: Apr 15 '21