0

I have this document in the MongoDB with the following structure stored inside result field

Mongo document

[   
    {
        "id" : "131429",
        "categoryId" : "3",
        "results" : [{              
                "id" : "yAHPPvo",
                "supplierId" : 31,
                "countryId" : "91",
                "cityId" : "91",
            }, {                
                "id" : "BAYYESB",
                "supplierId" : 31,
                "countryId" : "91",
                "cityId" : "91",
            }]
    },
    {
        "id" : "22534",
        "categoryId" : "2",
        "results" : [{              
                "id" : "DerrDSQ",
                "supplierId" : 14,
                "countryId" : "91",
                "cityId" : "91",
            }, {                
                "id" : "TTerySQ",
                "supplierId" : 5,
                "countryId" : "91",
                "cityId" : "91",
            }]
    }
]

Trying to figure out how to query and extract the object with key of "yAHPPvo", figured the first part to find the necessary document, but how do I extract the sub-object inside of it? I've seen on the Net that this is done with aggregation functions and unwinding, but just cannot seem to put my finger on it. I can convert it to an array if it makes it easier, but have tried both with little success.

Update

This is what I've tried so far from the duplicate link suggestion:

db.getCollection('searches').aggregate([
    {$match: {'result.id': '131429'}},
    {$project: {
        result: {$filter: {
            input: '$result',
            as: 'result',
            cond: {$eq: ['$$result.id', 'yAHPPvo']}
        }},
        _id: 0
    }}
])

but that returns 0 records.

Daniel Protopopov
  • 6,778
  • 3
  • 23
  • 39
  • What do you mean by "extract"? Can you be more specific about the end result you are after? `$unwind` is an operator that applies to "arrays", and these are not arrays. As for "converting" your structure, then that depends on what you want to do. So that is best stated in your question. – Neil Lunn Jun 07 '17 at 09:09
  • Thanks, I thought about it and updated the question. I'm after the object with the ID = yAHPPvo, I need to fetch it as a result of the query to MongoDB. – Daniel Protopopov Jun 07 '17 at 09:23
  • What update other than the value you are looking for? That doesn't actually tell us anything. I asked you to "explain what you mean by extract" and that means "please show us the result you expect". Also please do not use the "snippet" option when editing. Snippets are just for running examples of HTML / CSS and JavaScript. This is just a code block with a data structure in it. No snippets please. – Neil Lunn Jun 07 '17 at 09:26

0 Answers0