如何在嵌套数组中更新一个文档

如何在嵌套数组中更新一个文档

问题描述:

{
    "_id": "5e28b029a0c8263a8a56980a",
    "name": "Recruiter",
    "data": [
        {
            "_id": "5e28b0980f89ba3c0782828f",
            "targetLink": "https://www.linkedin.com/in/dan-kelsall-7aa0926b/",
            "name": "Dan Kelsall",
            "headline": "Content Marketing & Copywriting",
            "actions": [
                {
                    "result": 1,
                    "name": "VISIT"
                },
                {
                    "result": 1,
                    "name": "FOLLOW"
                }
            ]
        },
        {
            "_id": "5e28b0980f89ba3c078283426f",
            "targetLink": "https://www.linkedin.com/in/56wergwer/",
            "name": "56wergwer",
            "headline": "asdgawehethre",
            "actions": [
                {
                    "result": 1,
                    "name": "VISIT"
                }
            ]
        }
    ]
}

这是我的mongodb文件之一.我想更新data->actions->result 这就是我所做的

Here is one of my mongodb document. I'd like to update data->actions->result So this is what I've done

Campaign.updateOne({
    'data.targetLink': "https://www.linkedin.com/in/dan-kelsall-7aa0926b/",
    'data.actions.name': "Follow"
}, {$set: {'data.$.actions.result': 0}})

但是似乎没有更新任何内容,甚至无法通过此"data.actions.name"找到文档.

But it seems not updating anything and even it can't find the document by this 'data.actions.name'

您需要

You need the positional filtered operator since the regular positional operator ($) can only be used for one level of nested arrays:

Campaign.updateOne(
     { "_id": "5e28b029a0c8263a8a56980a", "data.targetLink": "https://www.linkedin.com/in/dan-kelsall-7aa0926b/" },
     { $set: { "data.$.actions.$[action].result": 0 } },
     { arrayFilters: [ { "action.name": "Follow" } ] }
)