本文介绍了如何获得 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 您的文件按价格".从那里,您$sort 他们按_id"升序并使用 $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 集合中的最低值?
发布评论