D
D
Dmitry Sudarkin2017-08-23 13:20:09
MongoDB
Dmitry Sudarkin, 2017-08-23 13:20:09

How to update a record in mongodb given a unique parameter?

Hello. There is an entry in mongodb

{
    "_id" : ObjectId("599aa4467745ffb9644da8eb"),
    "email" : "[email protected]",
    "series" : [ 
        {
            "id" : "58e52c4e89673a7a83438f1c",
            "letters" : [ 
                {
                    "id" : "1bki584500r0trtyie7700001",
                    "sented_at" : [ 
                        "2017-08-23 16:45"
                    ]
                }
            ]
        }
    ]
}

I need to update the entry by inserting an array into series, provided that the series with id 58e52c4e89673a7a83438f1c already exists, if it does not exist, then add it.
"series" : [ 
        {
            "id" : "58e52c4e89673a7a83438f1c",
            "letters" : [ 
                {
                    "id" : "1bki584500r0trtyie7700001",
                    "sented_at" : [ 
                        "2017-08-23 16:45"
                    ]
                },
                {
                    "id" : "1bki584500r0trtyie7700222",
                    "sented_at" : [ 
                        "2017-08-23 18:22"
                    ]
                }
            ]
        }
    ]

I do so
$update = [
      "id" => "58e52c4e89673a7a83438f1c",
             "letters" => [
                   [
                        "id" => "1bki584500r0trtyie77000022",
                         "sented_at" => [ 
                               "2017-08-23 16:45"
                          ]
                   ]
            ]
   ];

$contacts->where(['email' => '[email protected]'])->push(["series" => $update]);

It doesn't update as it should. It turns out that the series with "id" => "58e52c4e89673a7a83438f1c" is duplicated, but you need to register it in it or add it if it does not exist

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Philipp, 2017-08-26
@GrozInventor

You need to update with $addToSet.

db.getCollection('t1').update(
{
    _id: ObjectId("599aa4467745ffb9644da8eb"),
    "series.id": "58e52c4e89673a7a83438f1c",
},
    
{ $addToSet: {
        'series.$.letters': {
            "id" : "1bki584500r0trtyie7700002",
                    "sented_at" : [ 
                        "2017-08-23 16:46"
                    ]
        } 
    }
}
)

And instead of 'sented_at' use 'sent_at'.
The past form of the verb send is sent.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question