POOJA GUPTA
POOJA GUPTA

Reputation: 2355

Way to update multiple different sub documents with different values within single document in Mongodb using Python

I am working in Python with pandas dataframes and currently my dataframe is :

product_id  mock_test_id  q_id  q_correct_option  language_id   is_corr  is_p    is_m
    2790          2999     1                 1            1      1        1       1
    2790          2999     2                 1            1      1        1       1 
    2790          2999     3                 2            1      0        1       1
    2790          2999     4                 3            1      2        1       1
    2790          2999     5                 3            1      3        1       1

and the collection document is like :

{ "_id" : ObjectId("57eea81cd65b43a872024522"), 
  "langid" : 1, 
  "mocktest_id" : 2999, 
  "pid" : 2970, 
  "userid" : 1223, 
  "attempt" : { 
         "1" : { "seqid" : 1, 
                  "o" : NumberLong(1), 
                  "t" : NumberLong(749825), 
                  "is_m" : 1, 
                  "is_p" : 1, 
                  "is_corr" : 0 }, 
         "2" : { "seqid" : 2, 
                 "o" : NumberLong(2), 
                 "t" : NumberLong(749825), 
                 "is_m" : 1, 
                 "is_p" : 1, 
                 "is_corr" : 1 }
  }


}

Now I want to update this document at one go, wherein, within the 'attempt' object we have q_id as keys in it. q_id is also present in dataframe as can be seen from above. Now, corresponding to every mock_test_id, product_id, q_id I want to update is_p, is_m, is_corr fields at one go where is_p or is_corr field may or may not be present.

Right now, I am iterating over dataframe and updating row by row :

for index,row in stud_mock_result_df:
         db.UserAttemptData.update({'userid':user_id,'mocktest_id':mock_test_id,'pid':pid},{'$set':{'attempt.'+str(row['q_id'])+'.is_m':0,'attempt.'+str(row['q_id'])+'.is_p':1,'attempt.'+str(row['q_id'])+'.is_corr':row['is_corr']}})

How can I update it in one go ?

Upvotes: 0

Views: 155

Answers (1)

Sachin
Sachin

Reputation: 2922

Using one query you can set the same value to multiple objects of an array but to set different value to different objects you have to hit multiple queries.

In the case if you want to update multiple objects with same value then in that case use {multi: true} option.

     db.UserAttemptData.update(condition, update, {multi: true}).

Upvotes: 1

Related Questions