Reputation: 7114
In a MongoDB collection, I want to add a new object to an array which may or may not already exist, with the creation date of the object as one of the fields. Here's a barebones version of the structure of my test
collection, showing the result that I want to achieve:
{
"_id" : 1,
"parent" : {
"array_1" : [
{ "key" : "value_1"
, "created": ISODate(...)
}
]
}
}
In meteor mongo
, I create the parent with the following commands:
use test
db.test.insert({ _id: 1, parent: {} })
I can add a new array with the following command:
db.test.update(
{ _id: 1 }
, { $push: {
"parent.array_1": {
key: "value_1"
}
}
}
, { $currentDate:
{ "parent.array_1.$.created": true }
}
)
However, in the resulting array, the created
field is not added. I need to use a second command which refers to the array in the selection query:
db.test.update(
{ _id: 1
, "parent.array_1.key": "value_1"
}
, { $currentDate:
{ "parent.array_1.$.created": true}
}
)
Is there a way to insert the created
field at the same time as the array item that it belongs to, in a single command?
Upvotes: 0
Views: 544
Reputation: 28366
You are passing 3 arguments to update
. The second argument is supposed to be the update, and the third is supposed to be an options object. If you want to include the create time in the array element, make sure it is in the object that you are pushing on the array. Since you are using javascript, that could be:
db.test.update(
{ _id: 1 }
, { $push: {
"parent.array_1": {
key: "value_1",
created: new Date()
}
}
}
)
Upvotes: 1