使用Pymongo重命名收藏



我意识到可以使用

在mongodb中重命名一个集合
db["old_name"].renameCollection("new_name")

但是Pymongo中是否有等效的?我尝试了以下内容,但也没有用。

db["old_name"].rename_collection("new_name")

根据文档,该方法简单地命名为 rename

rename(new_name, session=None, **kwargs)
     new_name: new name for this collection
     session (optional): a ClientSession
     **kwargs (optional): additional arguments to the rename command may be passed as keyword arguments to this helper method (i.e. dropTarget=True)

可能是您可以在Pymongo中使用重命名,只需使用

db.oldname.rename('newname')

您可以检查链接:https://api.mongodb.com/python/current/api/pymongo/collection.html?highlight = rename

admin命令可以以类似的方式执行集合。

query = {
    'renameCollection': '<source_namespace>', 
    'to': '<target_namespace>',
}
client.admin.command(query)
   query = bson.son.SON([
       ('renameCollection', 't1.ccd'),
       ('to', 't2.ccd2'),
   ])
   print(query)
   self.mgclient.admin.command(query)

需要使用bson.son.son,如dict无序。请参考:

http://api.mongodb.com/python/current/api/bbson/son.html#bson.son.son.sonhttp://api.mongodb.com/python/current/api/pymongo/database.html

请注意,命令文档中的密钥顺序很重要( "动词"必须先出现(,因此需要多个键的命令(例如 FindandModify(应使用儿子或字符串和夸尔格的实例 而不是python dict。

最新更新