insert not duplicate data with Pymongo in mongodb

安稳与你 提交于 2019-12-08 12:20:53

问题


Now,I try to insert data with 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 be use forEach.but syntax error

yang


回答1:


If the hme key holds arrays of ObjectIds then you could try the $addToSet operator instead of the $push since it adds a value to an array unless the value is already present, in which case $addToSet does nothing to that array thus it only ensures that there are no duplicate items added to the set and does not affect existing duplicate elements:

get_db().users.update(
   {'_id':ObjectId(session['user_id'])},
   {
       '$addToSet':{
           'hme':ObjectId(id)
       }
   },
   upsert=True
)


来源:https://stackoverflow.com/questions/31043412/insert-not-duplicate-data-with-pymongo-in-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!