Raj
Raj

Reputation: 837

how to get the matching document inside a array in mongodb?

My collection is like this

{
 _id :"",
 name:[
  {
   firstName:"",
   lastName:"",
  }
 ]
}

i need to find the matching firstName in the documents. how to achieve this in a query ? I am new to mongodb.

Upvotes: 2

Views: 2175

Answers (3)

Sammaye
Sammaye

Reputation: 43884

@Sushant Gupta provided the right answer however I will add a little more flavour by saying that you can also do:

db.collection.find({'name.firstName': 'Raj'}, {'name.$':1})

to: matching firstName in the documents.

The key behind this is that MongoDB will treat single multikey occurances within document like normal flat fields allowing you to query down into them like this.

The second parameter you see is actually a projection ( http://docs.mongodb.org/manual/reference/projection/elemMatch/ ), it tells MongoDB to basically project out the FIRST (will need to use aggregation framework if you want more) matching name subdocument from the main one.

It is good to note that if you add two or more multikey fields like so:

db.collection.find({'name.firstName': 'Raj', 'name.lastName': ''}, {'name.$':1})

Then you will need to use $elemMatch, however, for small single field queries like this or where you intentionally mean to search all multikey fields in a document for two values, the dot notation ( http://docs.mongodb.org/manual/reference/glossary/#term-dot-notation ) works well.

Upvotes: 2

Amol M Kulkarni
Amol M Kulkarni

Reputation: 21639

This is what solves your problem:

db.MyCollection.find(  { name : { $elemMatch: { firstName : "valueGoesHere"} } } )

Upvotes: 0

Sushant Gupta
Sushant Gupta

Reputation: 9458

db.collection.find({name: {$elemMatch: {firstName: "Raj"}}});

For further details check out the documentation for $elemMatch

Upvotes: 2

Related Questions