way to update multiple different sub documents with different values within single document in mongodb using python
<p>I am working in Python with pandas dataframes and currently my dataframe is :</p>

<pre><code>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
</code></pre>

<p>and the collection document is like :</p>

<pre><code>{ "_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 }
  }


}
</code></pre>

<p>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. </p>

<p>Right now, I am iterating over dataframe and updating row by row : </p>

<pre><code>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']}})
</code></pre>

<p>How can I update it in one go ? Please Help someone. </p>

<p>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.</p>

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

<pre><code>     db.UserAttemptData.update(condition, update, {multi: true}).
</code></pre>

python mongodb pandas dataframe