Home > Blockchain >  How to know the last time a product has been updated MongoD?
How to know the last time a product has been updated MongoD?

Time:11-13

I am working on a project where I want to filter by the products that hasn't been updated in 2 months or a determinated date.(that don't have a new item price in the last 2 months or any other date I want to) I want to do the script in python.

All my db are json that follow this estructure:

And to access it i do mongo_client[db_name][coll_name] and then i normally use .find() or .aggregate()

{
    "_id" : ObjectId("6188f511091533324af78fbf"),
    "market" : "x",
    "product" : "apple",
    "item_price_history" : [ 
        {
            "item_price" : 219.0,
            "date" : ISODate("2021-04-08T15:30:43.000Z")
        }, 
        {
            "item_price" : 248.0,
            "date" : ISODate("2021-04-22T08:02:28.000Z")
}

Do you have any idea of how can I do that? I use the lastest version of Python and Robo 3T-1.4

Thanks in advance

CodePudding user response:

You can look at the data in the item_price_history to check when that field was last updated. But you don't seem to have a way to track when the other field were updated.

Going forward, you could try adding a pre-save hooks to store the last updated datetime if you're using an ODM like MongoEngine.

Refer pre_save method here.

CodePudding user response:

import dateutil.parser

list_to_sort = {
     "market" : "x",
     "product" : "apple",
     "item_price_history" : [
         {
             "item_price" : 219.0,
             "date" : "2021-04-08T15:30:43.000Z"
         },
         {
             "item_price" : 248.0,
             "date" : "2021-04-22T08:02:28.000Z"
         }]
}

candidates = list_to_sort.values()

for item in candidates:
    if isinstance(item,list):
        list_to_sort = item



def myfunc(item):
    time = dateutil.parser.parse(item["date"])
    return time.timestamp()

list_to_sort.sort(key=myfunc)
print(list_to_sort)

this will sort the list based on custom function myfunc

  • Related