Search code examples
mongodbpymongo

how to get distinct records from Mongodb using PYMONGO


My collection has 4 documents:

enter image description here

Both HCL and TCS are repeated twice with different values

I need to find all stocks with only latest values without repetition of stock

In the above example I need result:

[
    {
        "stock" : "HCL",
        "price" : 11
    },
    {
        "stock" : "TCS",
        "price" : 21
    }
]

It should ignore the previous values and only find the last one for each stock

Can it be done in Mongodb find query? I am using Python through pymongo


Solution

  • I solved it by :

    r  = coll_LTP.aggregate([
        {"$group": {
            "_id": "$stock",
            "price" :{"$last" : "$price"},
        }},
        # {"$sort": {
        #     "date": -1,
        # }}
      ])
    

    Thanks