本文介绍了如何获得MongoDB集合中的最低值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个名为product的MongoDB集合,该集合具有以下文档,如下所示.
I have a MongoDB collection called product which has the following documents as 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 to query the collection and only return documents that have the lowest price e.g
{ product: "Milk", barcode: 12345, price: 100, store: "BestBuy" } { product: "Milk", barcode: 12345, price: 100, store: "WalMart" }但是当我运行聚合查询时:
But when I run my aggregation query:
db.test.aggregate([{$match:{barcode:1234}},{$group: {_id:"$name", price: {$min:"$price"} } }])它仅返回一个文档.
推荐答案您需要 $group 按价格"列出您的文档.从那里,您以"_id"升序 $sort 订购并使用 $limit 返回第一个文档比具有最小值的文档要大.
You need to $group your documents by "price". From there, you $sort them by "_id" in ascending order and use $limit to return the first document which nothing other than the document with the minimum value.
db.products.aggregate([ { "$group": { "_id": "$price", "docs": { "$push": "$$ROOT" } }}, { "$sort": { "_id": 1 } }, { "$limit": 1 } ])产生类似:
{ "_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" } ] }更多推荐
如何获得MongoDB集合中的最低值?
发布评论