MadPhysicist
MadPhysicist

Reputation: 5831

Moving Embedded Document to an Array in Same Parent Document Mongo

I have a Mongo collection with the following structure of its objects:

{
  id: ,
  ...
  events: [{},{},{} ...]
  ...
  runtime: {
    field1: Date,
    field2: Date,
    field3: boolean
  }
}

When a certain route is queried, I would like to take field1 and field2 of the runtime embedded object and insert them as entries into the events array. That is, the members of the events array look like:

{
  field1: Date,
  field2: Date
}

How can I do this? I have been looking at the push operator, but am unsure if it is the right tool for this job.

Upvotes: 1

Views: 245

Answers (1)

Lakmal Vithanage
Lakmal Vithanage

Reputation: 2777

As i understand, You can do as follow,

db.col.update( { _id: id }, { $set: { $push: { events: { field1: Date, field2: Date } } } } )

Note

You have to use $set otherwise update operation will cause other parameters to be deleted. And the you push 'A' to 'B' like that,

{ $push: { B: A }} then A is, {field1: Date,field2: Date} and B is events.

Edit

Use this to update documents using it's own values. db.col.find().snapshot().forEach( function (ele) { db.col.update( { _id: id }, { $set: { $push: { events: { field1: ele.runtime.field1, field2: ele.runtime.field2 } } } }

});

Upvotes: 1

Related Questions