nb_nb_nb
nb_nb_nb

Reputation: 1381

For each from list insert item in mongo collection

I have a list of ids arr = [123, 456, 765...]

I need to do a for each of these:

I need to run a bunch of steps like grabbing some values from a MongoDB collection, then converting that into a list, and then making a change to the returned fields and inserting them back to a new collection.

How do I do this for a forEach of the id's in that list.

Here is the rest of functions I am running:

hello=col.find({'id':123}, {'_id':0})

for item in hello:
   to_ISO = datetime.strptime(item['created_dt'], "%Y-%m-%dT%H:%M:%S.%f%z")  

   list_audits = list(audit_pages_res)
   pprint(list_audits)

db.newcol.insert({date: to_ISO})

I want to do a forEach from arr, replace the id in hello do the rest of the functions I need and then insert the record and then move to the next item on the list.

Is there any way for me to do that?

Upvotes: 0

Views: 28

Answers (1)

Belly Buster
Belly Buster

Reputation: 8814

Hard to figure out exactly what you're trying to do but if you know the exact _id then no need to use a find and a loop; just use find_one(). start with:

arr = [123, 456, 765]

for arr_id in arr:
    hello=col.find_one({'id':arr_id}, {'_id':0})

    if hello is not None: # Need to check it found a record
        to_ISO = datetime.strptime(hello['created_dt'], "%Y-%m-%dT%H:%M:%S.%f%z") 

Upvotes: 1

Related Questions