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

79 Views Asked by At

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?

1

There are 1 best solutions below

6
dododo On BEST ANSWER

Use $out aggregation stage:

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

see playground