Adding a new property (in the last element of the array) in the mongodb inline document

I am using a mongo document as shown below:

{
        "_id" : ObjectId("59ccb655071d4c2ceebe190c"),
        "session_deatils" : [
                {
                        "session_start" : 1,
                        "session_complete" : 1,
                        "started_at" : ISODate("2017-09-28T08:42:19.770Z"),
                        "event_count" : 2
                },
                {
                        "session_start" : 1,
                        "session_complete" : 1,
                        "started_at" : ISODate("2017-09-28T08:53:08.618Z"),
                        "event_count" : 1
                },
                {
                        "session_start" : 1,
                        "session_complete" : 1,
                        "started_at" : ISODate("2017-09-28T09:19:42.726Z")
                }
        ],
        "session_id" : "12312312313123",
}

I want to add a new field and value of type "event_count" in the last element in the session details, which

        {
                "session_start" : 1,
                "session_complete" : 1,
                "started_at" : ISODate("2017-09-28T09:19:42.726Z")
        }

            and I want to update it and the array element should look like below:

        {
                "session_start" : 1,
                "session_complete" : 1,
                "started_at" : ISODate("2017-09-28T09:19:42.726Z"),
                "event_count" : 3
        }

I tried as below:

collection.update({"session_deatils.started_at":  datetime.datetime(2017, 9, 28, 9, 22, 3, 459000)}, {"$set":{"session_deatils.event_count":3}}) 

which adds a new property to the parrent file.

Is there any way I can achieve this? thanks in advance

+4
source share

Source: https://habr.com/ru/post/1686539/


All Articles