2

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.

3 Answers 3

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

For further details check out the documentation for $elemMatch

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

1 Comment

@Raj koi nahi bhai. It was my pleasure :)
2

@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.

Comments

0

This is what solves your problem:

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

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.