python - insert not duplicate data with Pymongo in mongodb -
now,i try insert data pymongo in mongoldb.
get_db().users.update({'_id':objectid(session['user_id'])},{'$push':{'hme':objectid(id)}},upsert=true)
but,the method produce duplicate objectid.before try find_one().
if not objectid(id) in get_db().users.find_one({'_id':objectid(session['user_id'])})['hme']: get_db().users.update({'_id':objectid(session['user_id'])},{'$push':{'hme':objectid(id)}},upsert=true)
better method request..
may use foreach.but syntax error
yang
if hme
key holds arrays of objectid
s try $addtoset
operator instead of $push
since adds value array unless value present, in case $addtoset
nothing array ensures there no duplicate items added set , not affect existing duplicate elements:
get_db().users.update( {'_id':objectid(session['user_id'])}, { '$addtoset':{ 'hme':objectid(id) } }, upsert=true )
Comments
Post a Comment