Clone a collection in MongoDB

后端 未结 8 585
有刺的猬
有刺的猬 2020-12-02 10:19

I want to clone a MongoDB collection and save it on the same server with a different name. So for example right now I have the following collections: demo1.categories, demo1

8条回答
  •  忘掉有多难
    2020-12-02 10:59

    If you're concerned about speed then I found that by using aggregate with $project and $out to be a 100 times faster, not sure if there are restrictions though, but you would have to create a set of fields that you'd want to copy For example:

    // Set of fields in the categories collection
    var setOfFields = {field1:1, field2:1.......}
    db.demo1.categories.aggregate([{ "$project": setOfFields},{ $out: "demo2.categories"}]);
    

    This copies (projects) the selected set of fields for all documents from demo1.categories to demo2.categories

提交回复
热议问题