databasemongodbnosqlnon-relational-database

How do I insert a document along with the result of a find query together in a collection in a single query in MongoDB?


Suppose I have a collection named oldCollection which has a record like

{
name: "XYZ"
}

Now I want to insert this data into a new collection named newCollection. But I also want to add another key-value field (suppose a boolean field exists) for this same record like :

{
name: XYZ
exists:true
}

I am using find query to extract the required data and insert it into the new collection but how can I add more fields (like exists in the above example) in the same record?


Solution

  • Use $out aggregation stage:

    db.collection.aggregate([
    {
      "$addFields": { "exists": true }
    },
    {
      "$out": "resultedCollection"
    }
    ])
    

    see playground