如果存在则将对象推入数组,否则在 MongoDB 中设置对象

6 arrays mongodb mongodb-query

这是我目前拥有的文件:

{
    "_id": "",
    "title": "My Watchlist",
    "series": [{
        "seriesId": 1,
        "following": true,
        "seasons": []
    }, {
        "seriesId": 1,
        "following": false,
        "seasons": []
    }]
}
Run Code Online (Sandbox Code Playgroud)

如您所见,目前有 2 个对象的 seriesId 为 1,但具有不同的以下布尔值。

如果查询与 _id 匹配,它应该将新对象推入系列,如果在“series”数组中已经存在具有相同“seriesId”的对象,它应该更改该对象中的字段,而不是添加新对象。

我目前有以下查询:

users.update(
    {"_id": req.body.userId},
    {
        "$push": {
            "series": {"seriesId": req.body.seriesId, "following": req.body.following}
        }
    }, (err, data) => {
        if (err)
            next(err);
    });
Run Code Online (Sandbox Code Playgroud)

如果我使用 $set 它不会添加原始对象,如果它还不存在,据我所知你不能同时使用 $push 和 $set?这可以以任何方式修复还是我必须重新考虑我的架构?

Ber*_*tel 11

您可以使用两个update查询:

  • 如果_id找到并且seriesId不在数组中,则将新项添加到数组中:

    db.series.update({
        "_id": req.body.userId,
        "series": {
            "$not": {
                "$elemMatch": {
                    "seriesId": req.body.seriesId
                }
            }
        }
    }, {
        $addToSet: {
            series: {
                "seriesId": req.body.seriesId,
                "following": req.body.following,
                "seasons": []
            }
        }
    }, { multi: true });
    
    Run Code Online (Sandbox Code Playgroud)
  • 如果_id找到并seriesId在数组中找到,则更新数组项:

    db.series.update({
        "_id": req.body.userId,
        "series.seriesId": req.body.seriesId
    }, {
        $set: {
            "series.$.following": req.body.following
        }
    }, { multi: true });
    
    Run Code Online (Sandbox Code Playgroud)