如何获得MongoDB集合中的最低值? [英] How can I get the lowest values in a MongoDB collection?

查看:76
本文介绍了如何获得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"} } }])

它仅返回一个文档.

推荐答案

您需要 $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集合中的最低值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆