Search code examples
mongodbmongodb-update

Push document as child and update timestamp in parent document


I have a document as following:

{
    "_id": ObjectId("507f191e810c19729de860ea"),
    "updateTimestamp": Date(1234567),
    "actions": [
        {
            "timestamp": Date(123456)
            "action": "FIRE"
        },
        {
            "timestamp": Date(1234567)
            "action": "HIDE"
        }
    ]
}

How can I add a child document to the actions array and update the updateTimestamp field of the parent document at the same time? The idea is that I later can sort such documents on their most recent action activity, as reflected by the updateTimestamp field.


Solution

  • As simple as:

    db.collection.updateOne(
        { _id: '[id here]'},
        {
            $set: {
                'updateTimestamp': '[timestampHere]'
            },
            $push: {
                'actions': [new record here]
            }
        }
     );