MongoDB: Search minimum, maximum in nested object with dynamic field name -
i have query minimum query
, maximum query
on below sample data set. in case fields names dynamic, below product_1
, product_2
...
{ "_id" : numberlong(540), "product_1" : { "ordercancelled" : 0, "orderdelivered" : 6 }, "product_2" : { "ordercancelled" : 3, "orderdelivered" : 16 }, "product_3" : { "ordercancelled" : 5, "orderdelivered" : 11 } }
i not getting idea how can in mongo field names dynamic, means in future there may other products created product_4
, product_5
same id
.
i need query gives me minimum value orderdelivered
, maximum value ordercancelled
, example in above document result orderdelivered:16
& ordercancelled:0
.
idea.
you should restructure document product documents in array:
{ "_id": numberlong(540), products: [ { "name": "product_1", "ordercancelled": 0, "orderdelivered": 6 }, { "name": "product_2", "ordercancelled": 3, "orderdelivered": 16 }, { "name": "product_3", "ordercancelled": 5, "orderdelivered": 11 } ] }
then you'll able issue normal max/min queries this:
db.test.aggregate([ { $match: { "_id" : numberlong(540) } }, { $unwind: "$products" }, { $group: { _id: "$_id", mindelivered: { $min: "$products.orderdelivered" }, maxcancelled: { $max: "$products.ordercancelled" } } } ])
Comments
Post a Comment