Pimongo insert inside the loop

I have a difficult problem with inserting pymongo inside a loop. Why the result is only the first record if I use insert () or the last record if I use save ().

from pymongo import Connection m = Connection(config.get('server')) mdb = m[config.get('db_name')] cond = { 'corp_fax_no' : u'5667767', 'corp_area_id' : 12L, 'corp_url' : u'http://www.example.com', 'corp_id' : 1L, 'corp_addr' : u'some thing', 'corp_post_no' : u'220940', 'corp_email' : u' 123@123.com ', 'corp_tel_no' : u'714-717-2265' } @tool.timeit def test_insert_mongo(): cn = '{0}'.format(config.get("coll_timetest")) coll = mdb[cn] for i in xrange(10000): print i cond.update({'corp_id':i}) coll.insert(cond) test_insert_mongo() 

I just enter 10,000 entries in Mongo, but I can only find one entry. Why?

+4
source share
1 answer

If the document passed to collection.insert() does not contain _id , it will be added to save (see pymongo api ). This means that after the first call in the document there is _id and, therefore, will not be added.

If you call collection.save() , the saved document is updated and you will get one document with the last value passed as corp_id.

A simple “fix” would be to remove the _id key from the dict at each iteration before calling .insert ():

 for i in xrange(10000): cond.update({'corp_id':i}) cond.pop('_id', None) coll.insert(cond) 
+5
source

All Articles