0

I'm working on the following document

{
"_id" : 123344223,
"firstName" : "gopal",
"gopal" : [ 
    {
        "uuid" : "123",
        "name" : "sugun",
        "sudeep" : [ 
            {
                "uuid" : "add32",
                "name" : "ssss"
            }, 
            {
                "uuid" : "fdg456",
                "name" : "gfg"
            }
        ]
    }, 
    {
        "uuid" : "222",
        "name" : "kiran"
    }
]
} 

I want to get my output as following

{
"_id" : 456,
"gopal" : [ 
    {
        "uuid" : "123",
        "name" : "sugun",
        "sudeep" : [ 
            {
                "uuid" : "add32",
                "name" : "ssss"
            }
        ]
    }
]
}

and I tried many things like

db.People.findOne({_id:123},{gopal:{$elemMatch:{uuid:"123",sudeep:{$elemMatch:{uuid:"add32"}}}}});

but whatever I tried it returns the document like this

{
"_id" : 123,
"gopal" : [ 
    {
        "uuid" : "123",
        "name" : "sugun",
        "sudeep" : [ 
            {
                "uuid" : "add32",
                "name" : "ssss"
            }, 
            {
                "uuid" : "fdg456",
                "name" : "gfg"
            }
        ]
    }
]
}

can you please help?

styvane
  • 49,879
  • 15
  • 119
  • 132
  • Possible duplicate of [Retrieve only the queried element in an object array in MongoDB collection](http://stackoverflow.com/questions/3985214/retrieve-only-the-queried-element-in-an-object-array-in-mongodb-collection) – styvane Jan 08 '16 at 08:16

2 Answers2

2

Are you aware of MongoDB aggregation pipeline?

> db.people.aggregate([
    {$match: {_id: 123}}, 
    {$unwind: "$gopal"}, 
    {$unwind: "$gopal.sudeep"}, 
    {$match: {"gopal.uuid": "123", "gopal.sudeep.uuid" : "add32"}}
 ])

Output

{
        "_id" : 123,
        "firstName" : "gopal",
        "gopal" : {
                "uuid" : "123",
                "name" : "sugun",
                "sudeep" : {
                        "uuid" : "add32",
                        "name" : "ssss"
                }
        }
}
styvane
  • 49,879
  • 15
  • 119
  • 132
0

Use $unwind in aggregation pipeline

db.People.aggregate([{$match:{_id:'123'}},{$match:{gopal.uuid:'123'}},{$unwind:'$sudeep'},{$match:{uuid:'add32'}}])

Ankush Tanwar
  • 209
  • 2
  • 4