Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB get SubDocument

I would like to retrieve a sub document from a document in MongoDB. I have the following document:

{
    "_id" : "10000",
    "password" : "password1",
    "name" : "customer1",
    "enabled" : true,
    "channels" : [ 
        {
            "id" : "10000-1",
            "name" : "cust1chan1",
            "enabled" : true
        }, 
        {
            "id" : "10000-2",
            "name" : "cust1chan2",
            "enabled" : true
        }
    ]
}

The result I would like is:

{
    "id" : "10000-1",
    "name" : "cust1chan1",
    "enabled" : true
}

However, the best I can do so far is using the following query:

db.customer.find({"channels.id" : "10000-1"}, {"channels.$" : 1, "_id" : 0})

But this gives me the following result:

{
    "channels" : [ 
        {
            "id" : "10000-1",
            "name" : "cust1chan1",
            "enabled" : true
        }
    ]
}

Does anyone know if it is possible to write a query that will give me my desired result? Any help would be much appreciated.

like image 910
Stuart Avatar asked Jan 14 '14 12:01

Stuart


People also ask

What is a subdocument in MongoDB?

Subdocuments are documents embedded in other documents. In Mongoose, this means you can nest schemas in other schemas. Mongoose has two distinct notions of subdocuments: arrays of subdocuments and single nested subdocuments.

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 query an array of objects in MongoDB?

To search the array of object in MongoDB, you can use $elemMatch operator. This operator allows us to search for more than one component from an array object.


1 Answers

You can do it with Aggregation Framework. Query will be something like :

db.customer.aggregate([
    {$unwind : "$channels"},
    {$match : {"channels.id" : "10000-1"}},
    {$project : {_id : 0, 
                 id : "$channels.id", 
                 name : "$channels.name", 
                 enabled : "$channels.enabled"}}
])
like image 149
Parvin Gasimzade Avatar answered Sep 30 '22 16:09

Parvin Gasimzade