25

Is it possible to use Mongo to query for entries that have a particular value in a field in an object in an array.

For example, let's say I want to find all objects where field1 has an array of objects, one of which has the field 'one' with a value of 1. This query should return the following object from my collection:

{_id: 0000, field1: [{one: 1, two: 2}, {one: 'uno', two: 'dos'}]}
2
  • Do you mean an array of documents? Commented Jun 12, 2013 at 21:04
  • Well it's an array of JSON objects. Commented Jun 12, 2013 at 21:24

2 Answers 2

36

I suppose what you need is:

db.collection.find( { field1: { $elemMatch: { one: 1 } } } );

http://docs.mongodb.org/manual/reference/operator/elemMatch/#op._S_elemMatch

Sign up to request clarification or add additional context in comments.

2 Comments

How about in a deep nested array
what's the syntax for saving the result of this query in a javascript list?
7

This is an old question, but a simpler way to perform this query is to use dot notation:

db.collection.find({'field1.one': 1})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.