What's the fastest way to copy a collection within the same database?

后端 未结 8 671
余生分开走
余生分开走 2020-11-30 19:01

I want to copy a collection within the same database and give it a different name - basically take a snapshot.

What\'s the best way to do this? Is

8条回答
  •  孤城傲影
    2020-11-30 19:20

    This is my implementation in python (pymongo):

    def copy_collection(client, from_db, from_coll, to_db=None, to_coll=None):
        to_db = from_db if to_db is None else to_db
        to_coll = from_coll if to_coll is None else to_coll
        assert (to_db != from_db or to_coll != from_coll), "Copy Error: Source and destination can't be same!"
        documents = client[from_db][from_coll].find()
        client[to_db][to_coll].insert_many([d for d in documents])
    

提交回复
热议问题