首页 > 解决方案 > 将文档作为子推送并更新父文档中的时间戳

问题描述

我有一份文件如下:

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

如何将子文档添加到actions数组并同时更新updateTimestamp父文档的字段?这个想法是,我稍后可以根据字段反映的最近操作活动对此类文档进行排序updateTimestamp

标签: mongodbmongodb-update

解决方案


很简单:

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

推荐阅读