Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query for a field in an object in array with Mongo?

Tags:

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'}]} 
like image 641
user1816679 Avatar asked Jun 12 '13 20:06

user1816679


People also ask

How do I query an array object in MongoDB?

To search the array of object in MongoDB, you can use $elemMatch operator. This operator allows us to search for more than one component from an array object.

How do I search for a specific field in MongoDB?

You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});

How do I pop a specific element from an array in MongoDB?

To remove an element, update, and use $pull in MongoDB. The $pull operator removes from an existing array all instances of a value or values that match a specified condition.


1 Answers

I suppose what you need is:

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

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

like image 180
Lucia Pasarin Avatar answered Sep 22 '22 16:09

Lucia Pasarin