0

Can someone please help me constructing and extracting data from below JSON using mongo query?

JSON:

{
"app": [{
    "appFamily": "default",
    "attributes": [{
            "name": "field1",
            "value": "field1value"
        },
        {
            "name": "field2",
            "value": "field2value"
        },
        {
            "name": "field3",
            "value": "field3value"
        }
    ],
    "nameApp": "AppName",
},
       {
    "appFamily": "default2",
    "attributes": [{
            "name": "field1",
            "value": "field1value"
        },
        {
            "name": "field2",
            "value": "field2value"
        },
        {
            "name": "field3",
            "value": "field3value"
        }
    ],
    "nameApp": "AppName2",
}]

}

I need to fetch fields and values where name = "field2" and "field3" along with "nameApp" value.

Expected output:

{
{
    {
        "name": "field2",
        "value": "field2value"
    }, {
        "name": "field3",
        "value": "field3value"
    },
    "name": "AppName",
}, {

    {
        "name": "field2",
        "value": "field2value"
    },
    {
        "name": "field3",
        "value": "field3value"
    },
    "name": "AppName2",

}

}

Any help would be highly appreciated. Thanks

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
Tarun
  • 35
  • 1
  • 1
  • 6

1 Answers1

0

Tarun, assuming "app" is your Collection, you could make this call using find with the $or and $elemMatch logical operators, like this:

db.app.find(
    { $or: [
        { attributes: { $elemMatch: { name: 'field2' } }},
        { attributes: { $elemMatch: { name: 'field3' } }}
    ] }
);

It might be difficult (or impossible) to return expected output you listed, I'm not sure. Are you okay with the attributes being returned in an Array?

If so, you can do that explicitly by including the name of the field and a 1 in the query like this:

db.app.find(
    { $or: [
        { attributes: { $elemMatch: { name: 'field2' } }},
        { attributes: { $elemMatch: { name: 'field3' } }}
      ]
    }, { attributes: 1, nameApp: 1}
);

If "app" is the document, you'll need to nest the query above with another $elemMatch operator - $elemMatch is what allows you to match elements of an array.

Stephen Gheysens
  • 293
  • 2
  • 12