mongodb - find_one() 查找不存在的重复项
问题描述
我正在尝试将远程 mongodb atlas 服务器复制到本地服务器。我通过一个 python 脚本执行此操作,该脚本还检查记录是否已经存在。我看到即使本地数据库是空的,我的脚本也会找到重复项,这些重复项不在远程 mongodb 地图集中(至少我找不到它们)。我对 mongodb 和 pymongo 不是很有经验,但我不知道我做错了什么。有时 Find_one() 会找到与以前完全相同的记录(所有字段都相同,即使是 _id)?
我从本地服务器中完全删除了该集合并再次尝试,但结果仍然相同。
UserscollectionRemote = dbRemote['users']
UserscollectionNew = dbNew['users']
LogcollectionRemote = dbRemote['events']
LogcollectionNew = dbNew['events']
UsersOrg = UserscollectionRemote.find()
for document in UsersOrg: # loop over all users
print(document)
if UserscollectionNew.find_one({'owner_id': document["owner_id"]}) is None: # check if already there
UserscollectionNew.insert_one(document)
UserlogsOrg = LogcollectionRemote.find({'owner_id': document["owner_id"]}) # get all logs from this user
for doc in UserlogsOrg:
try:
if LogcollectionNew.find_one({'date': doc["date"]}) is None: # there was no entry yet with this date
LogcollectionNew.insert_one(doc)
else:
print("duplicate");
print (doc);
except:
print("an error occured finding the document");
print(doc);
解决方案
你在第一个里面有第二个 for 循环;那可能会很麻烦。
另外,您应该调查 mongodump 和 mongorestore 以复制集合;除非您需要在代码中执行此操作,否则这些工具更适合您的用例。
推荐阅读
- node.js - 使用可扩展 Node.js/Express/MongoDB 的方法为 1v1 游戏匹配用户
- php - 如何在 Laravel 中运行原始查询
- unity3d - Unity - 2D 让精灵脚落在点击位置而不是精灵中心
- axon - 引起:java.sql.SQLSyntaxErrorException:表'test.snapshot_event_entry'不存在轴突
- mongodb - 将 TTL 设置为 Schema 上的属性
- flutter - 自定义形状 - 底部导航栏 - Flutter
- python - 为什么 python numpy 没有与 cotangens 相关的函数,例如 arccot?
- python - 无头模式下的 chromedriver 不显示已完成操作的任何文本输出
- unity3d - 无法让 Unity Physics2D.BoxCast(NonAlloc) 注册 RayCast 工作的命中
- python - 如何使用 python 进入特定应用程序?