Let’s try to begin this tutorial by creating a new document. Enter the following code to create a new document in the info collection.
1 2 3 4 5 6 7 |
db.info.insert({ "name" : { "first" : "John", "last" : "Maxwell" }, "age" : 38 }) |
Noticecd that the value in the “name” key is an embedded document. Let’s try to query the embedded document by using the normal qeury.
> db.info.find({"name" : {"first" : "John"}})
>
>
Now let’s try to query the embedded document by providing more key to query.
> db.info.find({"name" : {"first" : "John", "last" : "Maxwell"}})
{ "_id" : ObjectId("53f161559c081bda7a849e05"), "name" : { "first" : "John", "la
st" : "Maxwell" }, "age" : 38 }
{ "_id" : ObjectId("53f161559c081bda7a849e05"), "name" : { "first" : "John", "la
st" : "Maxwell" }, "age" : 38 }
Although quering by providing all key that exactly match the sub-document is working, you just find it’s too many work to do in order query the embedded document. You can skip this by using of dot notation (.) as a qualifier. Let’s try the following:
> db.info.find({"name.first" : "John"})
{ "_id" : ObjectId("53f161559c081bda7a849e05"), "name" : { "first" : "John", "la
st" : "Maxwell" }, "age" : 38 }
{ "_id" : ObjectId("53f161559c081bda7a849e05"), "name" : { "first" : "John", "la
st" : "Maxwell" }, "age" : 38 }
Querying Embedded Document in MongoDB