Search This Blog

Tuesday, December 24, 2013

Nested documents and the dot notation in find

Important note: This article is in relation to online MongoDB course. For more information about the course and other posts describing its content please check my main page here: M101P: MongoDB for Developers course

Nested documents

We can have a variable that represent another document with completely separate attributes and values.
 
> db.embeded.insert( {rado1:1, nestedDoc : { var1 : 1, str : "test"  } } )

> db.embeded.find()
{ "_id" : ObjectId("52b8e2aa8a25e81047ccb8c9"), "rado1" : 1, "nestedDoc" : { "var1" : 1, "str" : "test" } }
> db.embeded.find().pretty()
{
        "_id" : ObjectId("52b8e2aa8a25e81047ccb8c9"),
        "rado1" : 1,
        "nestedDoc" : {
                "var1" : 1,
                "str" : "test"
        }
}

Searching for embedded variables

This is the find criteria for the most outer document variable in the standard way we were doing so far.
 
> db.embeded.find( {rado1 : 1} )
{ "_id" : ObjectId("52b8e2aa8a25e81047ccb8c9"), "rado1" : 1, "nestedDoc" : { "var1" : 1, "str" : "test" } }

Taking this analogy this search unfortunately doesn't produce the expected result.
 
> db.embeded.find( {nestedDoc : { var1 :1 } } )
>

If you need to provide the argument for the find method that is an embedded documents you need to provide the exact variables it is built of. Pay attention to the order because if you mix it this will not work again. It doesn't work because MongoDB is looking for a variable with exactly this schema/syntax specified.
 
> db.embeded.find( {nestedDoc : { var1 :1, str: "test" } } )
{ "_id" : ObjectId("52b8e2aa8a25e81047ccb8c9"), "rado1" : 1, "nestedDoc" : { "var1" : 1, "str" : "test" } }
> db.embeded.find( {nestedDoc : { str: "test", var1 :1 } } )

Dot notation

To search for the embedded values we can use the "dot" notation.
 
> db.embeded.find( { "nestedDoc.var1" : 1 } )
{ "_id" : ObjectId("52b8e2aa8a25e81047ccb8c9"), "rado1" : 1, "nestedDoc" : { "var1" : 1, "str" : "test" } }

No comments:

Post a Comment