Deshwal
Deshwal

Reputation: 4152

How to query and update entries in MongoDB (Pymongo) effectively?

I have a function where if I pass in an MongoDB.Collection.Object, it might or might not give me a vector [1,2,3,4...]. First of all, I need to extract all the required queries and then update the entries based on each. Problem is that I have this sort of function:

def return_vector(q):
  # condition = my_logic
  if condition:
    return vector
  else:
    return None'

for q in db.coll_name.find({'a.b.c':{'$gt':0.4}}):
  vector = return_vector(q)
  if q:
    db.coll_name.update({'_id': q['_id']},{'$set': {'vector_v1': vector}})

Problem? It is taking too much time. How am I supposed to do it with in optimized manner effectively?

Upvotes: 0

Views: 34

Answers (1)

Gibbs
Gibbs

Reputation: 22964

You do multiple updates. It could be one of the reason for slowness.

You can combine multiple updates and send one request rot he server using bulkwrite. It would significantly reduce network round trip time.

Hope you don't have multiple write requests for the same document at the same time.

Upvotes: 1

Related Questions