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

三世轮回 提交于 2019-12-30 23:32:14

问题


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"} } }])

It only returns one document.


回答1:


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 } 
])

which produces something 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"
        }
    ]
}


来源:https://stackoverflow.com/questions/37501925/how-can-i-get-the-lowest-values-in-a-mongodb-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!