简体   繁体   中英

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.

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

有关更多详细信息,请查看$elemMatch文档

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

这是解决您的问题的方法:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM