Ask Your Question
4

How can one transfer documents from one collection to another in MongoDB?

asked 2023-05-18 18:17:31 +0000

devzero gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-05-18 18:19:02 +0000

pufferfish gravatar image

To transfer documents from one collection to another in MongoDB, one can use the "aggregate" method and specify the output collection. Here are the steps:

  1. Connect to the MongoDB server and select the database that contains the source collection and the one that will receive the transferred documents.

  2. Use the "aggregate" method and specify the source collection as the input.

  3. Use the "out" option to specify the output collection where the transferred documents will be stored.

  4. If necessary, use the "match" and "project" stages to filter and transform the documents.

  5. Execute the aggregation pipeline.

Here is an example code snippet that will transfer all documents from the "sourceCollection" to the "targetCollection" in the same database:

db.sourceCollection.aggregate([
  {
    $out: "targetCollection"
  }
])

Note that the "out" option will overwrite any existing documents in the target collection with the same "_id" field. If you want to preserve the existing documents, you can use a temporary collection as the output and then merge the collections manually.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-18 18:17:31 +0000

Seen: 12 times

Last updated: May 18 '23