9

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")

4 Answers 4

13

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)
3
  • 7
    yes, so using your example: db["old_name"].rename("new_name") Sep 23, 2018 at 15:58
  • Link to docs has changed, see my comment further down.
    – Timo
    May 10, 2022 at 9:48
  • Docs updated, in future please feel free to just edit the URL.
    – rrrr-o
    May 10, 2022 at 10:36
11

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

1
4

An admin command to rename a collection can be executed in like manner.

query = {
    'renameCollection': '<source_namespace>', 
    'to': '<target_namespace>',
}
client.admin.command(query)
0
   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.

1
  • ...but in the case of this question, with renameCollection, must the keys be ordered? it seems like perhaps no, a dict is fine...? Jul 26, 2019 at 6:35

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.