Weekly Updates

Let's join our newsletter!

Do not worry we don't spam!

How to copy one collection to another by adding a field in MongoDB?

Is there a way to copy one collection to another in MongoDB while adding a new field?

Yes, it is possible to copy one collection to another in MongoDB by adding a field using the $addFields pipeline stage in the aggregation framework. Here is an example of how you can do it:

Suppose we have two collections named source_collection and target_collection, and we want to copy data from source_collection to target_collection by adding a new field called new_field.

Sample source_collection documents:


    {
        "_id": 1,
        "name": "John",
        "age": 25
    },
    {
        "_id": 2,
        "name": "Jane",
        "age": 30
    },
    {
        "_id": 3,
        "name": "Bob",
        "age": 40
    }


We want to copy this collection to a new collection named target_collection by adding a new field new_field which contains a string value.

The following MongoDB aggregation pipeline can be used to achieve this:


    db.source_collection.aggregate([
        {
            $addFields: {
                new_field: "new value"
            }
        },
        {
            $out: "target_collection"
        }
    ])


This pipeline adds a new field called new_field to each document in the source_collection with a value of "new value". The $out stage then writes the output to the target_collection.

How to copy one collection to another by adding a field in MongoDB?


The resulting documents in target_collection will look like this:

   
    {
        "_id": 1,
        "name": "John",
        "age": 25,
        "new_field": "new value"
    },
    {
        "_id": 2,
        "name": "Jane",
        "age": 30,
        "new_field": "new value"
    },
    {
        "_id": 3,
        "name": "Bob",
        "age": 40,
        "new_field": "new value"
    }

Learn to code with AKS Techies

Weekly Updates

Let's join our newsletter!

Do not worry we don't spam!