mongoose
mongoose copied to clipboard
Query on array of array object in mongodb
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..
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" } ] }
>
Perhaps you're looking for the $elemMatch operator? https://docs.mongodb.com/manual/reference/operator/projection/elemMatch/