简体   繁体   English

使用 Pymongo 重命名集合

[英]Renaming a Collection Using Pymongo

I realize that a collection can be renamed in MongoDB using我意识到可以在 MongoDB 中使用

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

But is there an equivalent in PyMongo?但是 PyMongo 中是否有等价物? I tried the following, but it didn't work either.我尝试了以下方法,但也没有用。

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

According to the documentation , the method is simply named rename .根据文档,该方法简称为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)

May be you can use rename in pymongo, just use可能你可以在 pymongo 中使用 rename ,只需使用

db.oldname.rename('newname')

You can check the link: https://api.mongodb.com/python/current/api/pymongo/collection.html?highlight=rename可以查看链接: https://api.mongodb.com/python/current/api/pymongo/collection.html?highlight=rename

An admin command to rename a collection can be executed in like manner.可以以类似方式执行重命名集合的管理命令。

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)

Need to use bson.son.SON, as dict is unordered.需要使用 bson.son.SON,因为 dict 是无序的。 Please refer to:请参阅:

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

Note the order of keys in the command document is significant (the “verb” must come first), so commands which require multiple keys (eg findandmodify) should use an instance of SON or a string and kwargs instead of a Python dict.请注意命令文档中键的顺序很重要(“动词”必须在前),因此需要多个键的命令(例如 findandmodify)应该使用 SON 实例或字符串和 kwargs 而不是 Python dict。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM