I have a inventory
collection with documents as shown below:
{
_id: 1,
item: "abc",
stock: [
{ size: "S", color: "red", quantity: 25 },
{ size: "M", color: "blue", quantity: 50 }
]
}
{
_id: 2,
item: "def",
stock: [
{ size: "S", color: "blue", quantity: 20 },
{ size: "M", color: "black", quantity: 10 },
{ size: "L", color: "red", quantity: 2 }
]
}
{
_id: 3,
item: "ijk",
stock: [
{ size: "M", color: "blue", quantity: 15 },
{ size: "L", color: "blue", quantity: 100 }
]
}
...
I have created compound multikey index on:
db.inventory.createIndex( { "stock.size": 1, "stock.quantity": 1 } )
I want to query for docs where stock.size: "M"
and all docs are sorted by it’s quantity in increasing order.
Expected result: [doc_2, doc_3, doc_1]
I am using query: db.inventory.find( { "stock.size": "M" } ).sort( { "stock.quantity": 1 } )
, but it’s not returning results in sorted order as expected above.
Can someone please help here, how I can achieve same.
Thanks!!