简体   繁体   中英

Update all documents in cursor with .limit() and .sort()

I have a fairly complicated query in pymongo, which looks like that:

frames = collection.find(
        {
            "inspectionId": inspectionId,
            "timestamp": 
                {
                    "$lt": time.time() - 3600
                }
        }
    ).limit(100).sort('img', 1)

Now I'd like to update the timestamp field in all of the documents the cursor frames points to. Right now I'm iterating through the cursor and set the timestamp for each document:

for frame in frames:
    collection.update_one(
        {
            "_id" : frame["_id"]
        },
        {
            "$set" :
                {
                    "timestamp": time.time()
                }
        }
     )

However, this does not seem very efficient, as it takes quite some time. Is there a handy way to update all documents at once, that are stored in a pymongo cursor?

Edit : it's not a duplicate as I'm using .limit() and .sort() , which are not compatible with the update option {multi: true} .

As you said they are in pymongo cursor (or data is at application end). Iterate over them, update your frames and make a bulk save call.

One more thing I'm not getting your use case. Why for update thing you are opting for limit and sort. If these are not required then you can directly go for update with multi=true

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM