Reputation: 121
I realize that a collection can be renamed in MongoDB using
db["old_name"].renameCollection("new_name")
But is there an equivalent in PyMongo? I tried the following, but it didn't work either.
db["old_name"].rename_collection("new_name")
Upvotes: 12
Views: 11201
Reputation: 141
May be you can use rename in pymongo, just use
db.oldname.rename('newname')
You can check the link: https://api.mongodb.com/python/current/api/pymongo/collection.html?highlight=rename
Upvotes: 14
Reputation: 2516
According to the documentation, the method is simply named 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)
Upvotes: 15
Reputation: 387
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. Please refer to:
http://api.mongodb.com/python/current/api/bson/son.html#bson.son.SON http://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 (e.g. findandmodify) should use an instance of SON or a string and kwargs instead of a Python dict.
Upvotes: 0
Reputation: 38962
An admin command to rename a collection can be executed in like manner.
query = {
'renameCollection': '<source_namespace>',
'to': '<target_namespace>',
}
client.admin.command(query)
Upvotes: 4