Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a specific embedded document inside a MongoDB collection? [duplicate]

Tags:

mongodb

I have a collection Notebook which has embedded array document called Notes. The sample

document looks like as shown below.

{ "_id" : ObjectId("4f7ee46e08403d063ab0b4f9"), "name" : "MongoDB", "notes" : [             {               "title" : "Hello MongoDB",               "content" : "Hello MongoDB"             },             {               "title" : "ReplicaSet MongoDB",               "content" : "ReplicaSet MongoDB"             }          ] } 

I want to find out only note which has title "Hello MongoDB". I am not getting what should

be the query. Can anyone help me.

like image 264
Shekhar Avatar asked Apr 06 '12 13:04

Shekhar


People also ask

How do I fetch a nested document in MongoDB?

Accessing embedded/nested documents – In MongoDB, you can access the fields of nested/embedded documents of the collection using dot notation and when you are using dot notation, then the field and the nested field must be inside the quotation marks.

How do I duplicate a document in MongoDB?

To clone a document, hover over the desired document and click the Clone button. When you click the Clone button, Compass opens the document insertion dialog with the same schema and values as the cloned document. You can edit any of these fields and values before you insert the new document.

What should we embed one document within another in MongoDB?

An embedded, or nested, MongoDB Document is a normal document that's nested inside another document within a MongoDB collection. Embedded documents are particularly useful when a one-to-many relationship exists between documents.


1 Answers

You can do this with mongo version higher 2.2

the query like this:

db.coll.find({ 'notes.title': 'Hello MongoDB' }, {'notes.$': 1}); 

you can try with $elemMatch like Justin Jenkins

like image 164
kop Avatar answered Oct 28 '22 23:10

kop