在 mongodb 中使用 Pymongo 插入不重复的数据 [英] insert not duplicate data with Pymongo in mongodb

查看:87
本文介绍了在 mongodb 中使用 Pymongo 插入不重复的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在,我尝试在 mongoldb 中使用 pymongo 插入数据.

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)

但是,该方法会产生重复的 ObjectID.在尝试 find_one() 之前.

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)

更好的方法请求..

可能用于 forEach.but 语法错误

may be use forEach.but syntax error

推荐答案

如果 hme 键包含 ObjectId 的数组,那么您可以尝试 $addToSet 运算符而不是$push 因为它会向数组添加一个值,除非该值已经存在,在这种情况下 $addToSet 对该数组不执行任何操作,因此它仅确保没有添加到集合中的重复项,并且不会影响现有的重复元素:

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
)

这篇关于在 mongodb 中使用 Pymongo 插入不重复的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆