如何获得 MongoDB 集合中的最低值?

编程入门 行业动态 更新时间:2024-10-24 14:16:09
本文介绍了如何获得 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 集合中的最低值?

本文发布于:2023-11-22 20:05:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1618821.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何获得   低值   MongoDB

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!