1

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.

1 Answer 1

1

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 } } } }

});

Sign up to request clarification or add additional context in comments.

2 Comments

Yes, but how does the push command know where to get field1 and field2?
I am not trying to push field1, and field2 which I create on the fly. Instead, these fields are already there when the route is executed. Upon the execution, I would like to move or copy these fields to the events array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.