How to get data from mongodb collection by mapping data in subdocu?

I have a mongodb collection with data like

   var data = [
{
    name: 'test1',
    attributes: [
        {
            name: 'color',
            value: 'red'
        },
        {
            name: 'size',
            value: 'L'
        }
    ]
},
{
    name: 'test2',
    attributes: [
        {
            name: 'color',
            value: 'blue'
        },
        {
            name: 'size',
            value: 'S'
        }
    ]
},
{
    name: 'test3',
    attributes: [
        {
            name: 'color',
            value: 'red'
        },
        {
            name: 'size',
            value: 'S'
        }
    ]
}

      

]

How do you query the database so that it returns documents matching the attribute name "color" with the value "red" and the attribute name "size" with the value "L"?

means it should return

 var output = [
{
    name: 'test1',
    attributes: [
        {
            name: 'color',
            value: 'red'
        },
        {
            name: 'size',
            value: 'L'
        }
    ]
}

      

]

+3


source to share


1 answer


You can use the operator $and

in your query find

.



db.collection.find({$and:[{"attributes.name":"color","attributes.value":"red"}, 
                          {"attributes.name":"size","attributes.value":"L"}]})

      

+2


source







All Articles