mongoose icon indicating copy to clipboard operation
mongoose copied to clipboard

Query on array of array object in mongodb

Open Ashh007 opened this issue 10 years ago • 2 comments

Following is my product collection in mongodb..


{
    "_id" : ObjectId("56d42389db70393cd9f47c22"),
    "sku" : "KNITCHURI-BLACK",
    "options" : [
        {
            "sku" : "KNITCHURI-BLACK-M",
            "stores" : [
                {
                    "code" : "6",
                    "quantity" : 0
                },
                {
                    "code" : "10",
                    "quantity" : 26
                }
            ],
            "ean_code" : "2709502",
            "size" : "M"
        },
        {
            "sku" : "KNITCHURI-BLACK-S",
            "stores" : [
                {
                    "code" : "6",
                    "quantity" : 0
                },
                {
                    "code" : "10",
                    "quantity" : 30
                }
            ],
            "size" : "S"
        }
    ]
}

want query on where { 'options.stores.code' : '6' } and { 'options.stores.quantity' : { $gt : 0 } }, How i query on this collection then i got response? Kindly help on this issue..

Ashh007 avatar Jul 10 '16 10:07 Ashh007

Works fine for me in the mongodb shell:

> db.test.insertOne(
... {
...     "_id" : ObjectId("56d42389db70393cd9f47c22"),
...     "sku" : "KNITCHURI-BLACK",
...     "options" : [
...         {
...             "sku" : "KNITCHURI-BLACK-M",
...             "stores" : [
...                 {
...                     "code" : "6",
...                     "quantity" : 0
...                 },
...                 {
...                     "code" : "10",
...                     "quantity" : 26
...                 }
...             ],
...             "ean_code" : "2709502",
...             "size" : "M"
...         },
...         {
...             "sku" : "KNITCHURI-BLACK-S",
...             "stores" : [
...                 {
...                     "code" : "6",
...                     "quantity" : 0
...                 },
...                 {
...                     "code" : "10",
...                     "quantity" : 30
...                 }
...             ],
...             "size" : "S"
...         }
...     ]
... })
> db.test.find({ 'options.stores.quantity' : { $gt : 0 } })
{ "_id" : ObjectId("56d42389db70393cd9f47c22"), "sku" : "KNITCHURI-BLACK", "options" : [ { "sku" : "KNITCHURI-BLACK-M", "stores" : [ { "code" : "6", "quantity" : 0 }, { "code" : "10", "quantity" : 26 } ], "ean_code" : "2709502", "size" : "M" }, { "sku" : "KNITCHURI-BLACK-S", "stores" : [ { "code" : "6", "quantity" : 0 }, { "code" : "10", "quantity" : 30 } ], "size" : "S" } ] }
> 

vkarpov15 avatar Jul 10 '16 21:07 vkarpov15

Perhaps you're looking for the $elemMatch operator? https://docs.mongodb.com/manual/reference/operator/projection/elemMatch/

vkarpov15 avatar Jul 10 '16 21:07 vkarpov15