[英]How can I backup and restore MongoDB by using pymongo?
pymongo是否提供API来启用集合和行的备份或导出?
Let me answer this question in two parts 让我分两部分回答这个问题
As of now, No. It does not provide a binding method for backup/mongodump 截至目前,不是。它没有为备份/ mongodump提供绑定方法
Yes. 是。 lets assume we have a collection col with the following documents in it
假设我们有一个集合col,其中包含以下文档
{
'price':25,
'name':'pen'
},
{
'price':20,
'name':'pencil'
},
{
'price':10,
'name':'paper'
},
{
'price':25000,
'name':'gold'
}
Our aim is to backup all documents which satisfy the condition that their price is less than 100. Using pymongo's find function. 我们的目标是备份满足其价格低于100的条件的所有文件。使用pymongo的查找功能。 this can be done by
这可以通过
db.col.find({'price':{'$lt': 100}})
The above code returns a cursor object. 上面的代码返回一个游标对象。 All the documents that we need for the backup is in that cursor object.
我们备份所需的所有文档都在该游标对象中。
A simple way to insert all the documents will be to recursively call the documents one by one and to insert them. 插入所有文档的一种简单方法是逐个递归调用文档并插入它们。
But a far better method is to use the list() on the cursor and to insert all the documents in one go. 但更好的方法是使用光标上的list()并一次性插入所有文档。
cursor = db.col.find({'price':{'$lt': 100}})
db.backup.insert(list(cursor))
The backup collection's content will be 备份集合的内容将是
{
'price':25,
'name':'pen'
},
{
'price':20,
'name':'pencil'
},
{
'price':10,
'name':'paper'
}
If there is no requirement to limit the entries to the backup. 如果没有要求将条目限制为备份。 One can use an empty find()
可以使用空的find()
cursor = db.col.find()
db.backup.insert(list(cursor))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.