I have a document in the following form:
{
"_id" : ObjectId("4d2d8deff4e6c1d71fc29a07"),
"user_id" : "714638ba-2e08-2168-2b99-00002f3d43c0",
"events" : [
{
"profile" : 10,
"data" : "....."
}
{
"profile" : 10,
"data" : "....."
}
{
"profile" : 20,
"data" : "....."
}
...
]
}
I'd like to have some sort of upsert
statement. It needs to add an event
to the events
array for user_id
in case there is already such doc exist, else it needs to create the doc with the event
item.
Can that be done?
In MongoDB, the $push operator is used to appends a specified value to an array. If the mentioned field is absent in the document to update, the $push operator add it as a new field and includes mentioned value as its element. If the updating field is not an array type field the operation failed.
In order to create a document if it doesn't already exist, you need to pass { upsert : true } in the options hash as it defaults to false . i.e. update is deprecated. Use updateOne, updateMany, or bulkWrite instead.
So, Adding a new field to an array is possible by using the update operation. $push operator is used to insert the field inside the array and if we want to add multiple fields, use $each inside $push.
MongoDB provides different types of array update operators to update the values of the array fields in the documents and $push operator is one of them. This operator is used to append a specified value to an array. Syntax: { $push: { <field1>: <value1>, ... } }
You can do upserts in Mongo, see "Upserts with Modifiers" from the Mongo doc:
You may use upsert with a modifier operation. In such a case, the modifiers will be applied to the update criteria member and the resulting object will be inserted.
The query you need will look like:
db.events.update( { "user_id" : "714638ba-2e08-2168-2b99-00002f3d43c0" },
{ $push : { "events" : { "profile" : 10, "data" : "X"}}}, {"upsert" : true});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With