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

前端 未结 1 1846
鱼传尺愫
鱼传尺愫 2021-01-20 00:51

I have a MongoDB collection called product which has the following documents as seen below.

{
    \"product\" : \"Milk\",
    \"barcode\" : 12345,
    \"pric         


        
相关标签:
1条回答
  • 2021-01-20 01:04

    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"
            }
        ]
    }
    
    0 讨论(0)
提交回复
热议问题