gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 09:39:23 28 4
gpt4 key购买 nike

这是我目前拥有的文件:

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

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

如果查询与 _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);
});

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

最佳答案

您可以使用两个 update 查询:

  • 如果找到 _idseriesId 不在数组中,则将新项目添加到数组中:

    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 });

关于arrays - 如果存在则将对象插入数组,否则在 MongoDB 中设置对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41332096/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com