How can I get the lowest values in a MongoDB collection? -


i have mongodb collection called product has following documents seen below.

{     "product" : "milk",     "barcode" : 12345,     "price" : 100,     "store" : "bestbuy" }, {     "product" : "milk",     "barcode" : 12345,     "price" : 100,     "store" : "walmart" }, {     "product" : "milk",     "barcode" : 12345,     "price" : 130,     "store" : "target" }, {     "product" : "milk",     "barcode" : 12345,     "price" : 500,     "store" : "game" } 

i wish query collection , return documents have lowest price e.g

{      product: "milk",     barcode: 12345,      price: 100,      store: "bestbuy" } {      product: "milk",     barcode: 12345,      price: 100,     store: "walmart" } 

but when run aggregation query:

db.test.aggregate([{$match:{barcode:1234}},{$group: {_id:"$name", price:  {$min:"$price"} } }]) 

it returns 1 document.

you need $group documents "price". there, $sort them "_id" in ascending order , use $limit return first document nothing other document minimum value.

db.products.aggregate([      { "$group": {          "_id": "$price",          "docs": { "$push": "$$root" }      }},     { "$sort": { "_id": 1 } },      { "$limit": 1 }  ]) 

which produces like:

{     "_id" : 100,     "docs" : [         {             "_id" : objectid("574a161b17569e552e35edb5"),             "product" : "milk",             "barcode" : 12345,             "price" : 100,             "store" : "bestbuy"         },         {             "_id" : objectid("574a161b17569e552e35edb6"),             "product" : "milk",             "barcode" : 12345,             "price" : 100,             "store" : "walmart"         }     ] } 

Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

java - Digest auth with Spring Security using javaconfig -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -