Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongodb - create doc if not exist, else push to array

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?

like image 373
LiorH Avatar asked Jan 23 '11 16:01

LiorH


People also ask

How do you push an object into an array in MongoDB query?

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.

Does MongoDB Update create if not exists?

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.

How do I add a field to an array in MongoDB?

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.

What is $Push in MongoDB?

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


1 Answers

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});
like image 130
Javier Ferrero Avatar answered Oct 23 '22 15:10

Javier Ferrero