首页 > 解决方案 > 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);

标签: mongodbpymongo

解决方案


你在第一个里面有第二个 for 循环;那可能会很麻烦。

另外,您应该调查 mongodump 和 mongorestore 以复制集合;除非您需要在代码中执行此操作,否则这些工具更适合您的用例。


推荐阅读