问题
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 ObjectId
s 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