如何使用pymongo从MongoDB复制一个集合并将其粘贴到另一个空集合? [英] How can I copy one collection from MongoDB using pymongo and paste to another empty collection?

查看:879
本文介绍了如何使用pymongo从MongoDB复制一个集合并将其粘贴到另一个空集合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  1. 我要复制完整的收藏集(例如,名称"home").
  2. 然后在"home"集合中进行一些更改或删除其中的文档(不是集合).
  3. 然后将已更改的"home"集合从项目1替换为其默认状态.

我下一步:

db = client["database"]
home = db['home'].find()  # get collection.
db['home'].remove({})  # remove doc from home
for i in home:
      self.db['home'].insert(i)

但是集合为空.

推荐答案

您的代码示例的问题是find()返回

The problem with your code example is that find() returns a database cursor to the collection, not all documents in the collection. So when you remove all documents from the home collection, the cursor will also point to an empty collection.

为了将一个集合复制到同一服务器中的另一个集合,您可以利用 MongoDB聚合运算符 $ match $ out

In order to copy a collection to another collection in the same server, you can utilise MongoDB Aggregation operator $match and $out

pipeline = [ {"$match": {}}, 
             {"$out": "destination_collection"},
]
db.source_collection.aggregate(pipeline)

使用示例代码,立即,您可以执行

Using your example code, now you can do

source = db["source_collection"]
destination = db["destination_collection"]

# Remove all documents, or make modifications. 
source.remove({}) 

# Restore documents from the source collection.  
for doc in destination: 
      source.insert(doc)
# or instead you can just use the same aggregation method above but reverse the collection name. 

注意: db.从MongoDB v3.0开始,不推荐使用collection.copyTo().

如果您想复制到另一台MongoDB服务器,则可以使用 db.cloneCollection().在PyMongo中,它将是以下命令:

If you would like to copy to another MongoDB server, you can utilise db.cloneCollection(). In PyMongo it would be a command such below:

db.command("cloneCollection", **{'collection': "databaseName.source_collection", 'from': "another_host:another_port"})

根据您的总体目标,您可能会发现 MongoDB备份方法有用.

Depending on your overall goal, you may find MongoDB BackUp methods useful.

这篇关于如何使用pymongo从MongoDB复制一个集合并将其粘贴到另一个空集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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