MongoDB更新数组中的对象,该数组位于另一个数组中。

3

模型结构:

{ _id: String, calc: [ { preset: String, datasets: [ { _id: String } ] } ] }

API路由:

router.put('/:gameId/:preset/:datasetId', (req, res) => {
  Game.findOneAndUpdate({ _id: req.params.gameId, 'calc.preset': req.params.preset, 'calc.datasets._id': req.params.datasetId },
    { $set: { 'calc.$.datasets.$': req.body } })
    .then(() => res.status(200).json({ ...req.body, _id: req.params.datasetId }))
    .catch(err => res.status(500).json({ error: err }));
});

如果要更新calc数组中的对象,则需要: $set: {'calc.$': newCalc},因此我采用了同样的方法来更新位于对象内部的数据集数组中的对象,该对象又位于calc数组内部的另一个对象中,但是,$set:{'calc.$.datasets.$':newDataset}不能正常工作。
如何更新具有req.params.preset预设的calc数组对象中的数据集数组内部具有_id:req.params.datasetId的对象?
简而言之:{calc:[{datasets:[ {将此对象设置为新数据集} ]}]}
1个回答

1

您可以使用$[]全部位置来更新嵌套数组元素,有关$[]的Mongo文档

查询

db.t14.update(
   {},
   { $set: { "calc.$[].datasets.$[elem].name": "updated" } },
   { arrayFilters: [  { "elem": "x1" } ], multi: true}
)

带有文档的示例集合

> db.t14.findOne()
{
        "_id" : 1,
        "calc" : [
                {
                        "preset" : "abc",
                        "datasets" : [
                                {
                                        "_id" : "x1",
                                        "name" : "n1"
                                },
                                {
                                        "_id" : "x2",
                                        "name" : "n2"
                                }
                        ]
                }
        ]
}

更新
> db.t14.update({},{$set: { "calc.$[].datasets.$[elem].name": "newname" } },{ arrayFilters: [{ "elem.name": "n1" }], multi: true})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

发布更新
> db.t14.findOne()
{
        "_id" : 1,
        "calc" : [
                {
                        "preset" : "abc",
                        "datasets" : [
                                {
                                        "_id" : "x1",
                                        "name" : "newname"
                                },
                                {
                                        "_id" : "x2",
                                        "name" : "n2"
                                }
                        ]
                }
        ]
}
>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接