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'}]}
user1816679
  • 845
  • 3
  • 11
  • 19

2 Answers2

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

Lucia Pasarin
  • 2,268
  • 1
  • 21
  • 37
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})
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471