【问题标题】:Push object into array if exists otherwise set object in MongoDB如果存在则将对象推送到数组中,否则在 MongoDB 中设置对象
【发布时间】:2017-05-10 23:14:57
【问题描述】:

这是我目前拥有的文件:

{
    "_id": "",
    "title": "My Watchlist",
    "series": [{
        "seriesId": 1,
        "following": true,
        "seasons": []
    }, {
        "seriesId": 1,
        "following": false,
        "seasons": []
    }]
}

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

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

我目前有以下查询:

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

如果我使用 $set,如果它最初不存在,它不会添加对象,据我所知,你不能同时使用 $push 和 $set? 可以以任何方式解决此问题,还是我必须重新考虑我的架构?

【问题讨论】:

标签: arrays mongodb mongodb-query


【解决方案1】:

你可以使用两个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 });
    
  • 如果找到_id,并且在数组中找到seriesId,则更新数组项:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-15
    • 2021-05-30
    • 1970-01-01
    • 1970-01-01
    • 2018-08-09
    • 2021-08-30
    • 1970-01-01
    相关资源
    最近更新 更多