gpt4 book ai didi

node.js - 如果存在则更新 MongoDB 中的嵌套对象,否则添加它

转载 作者:行者123 更新时间:2023-12-03 12:17:37 25 4
gpt4 key购买 nike

我在 mongoDB 中有一个这样的 json 文档:

 { "_id" : ObjectId("57ed88c0965bedd2b11d5727"),
"refid" : 2,
"votes" : [
{ "ip" : "127.0.2.1", "rating" : 5 },
{ "ip" : "127.0.3.1", "rating" : 2 },
{ "ip" : "127.59.83.210", "rating" : 50 },
{ "ip" : "127.56.26.191", "rating" : 5 },
{ "ip" : "127.59.83.210", "rating" : 5 },
{ "ip" : "127.59.83.210", "rating" : 30 }
]
}

如果 IP 存在,我想更新发现的记录,而不是为每个 IP 创建重复项,如果不存在,则添加一个新条目。关于如何进行类似操作有很多问题,但我找不到一个能问这么简单的问题。我正在 Node.js 中尝试这个:
db.collection('ratings').update( { "refid":refid, "votes.ip":ip },
{
$push: { votes: { "ip":ip, "rating":rating }
}
})

但是当我从同一个 IP 投票时,它只会不断添加新条目。

注意:我没有使用 Mongoose 。

如果我的问题过于初级,我深表歉意,我对 MongoDB 还很陌生。我只是想知道是否有一种很好的方法可以做到这一点,而不是以编程方式遍历“投票”中的每条记录。谢谢!

编辑:我问的是目前不可能的,我在下面标记了一个正确的答案,其中包含解释和指向 MongoDB 票证的链接以进行改进。

至于我的问题中的场景,下面的代码对我有用。我不知道它在性能方面的好坏,但它涵盖了所有这些场景:
  • 如果该记录根本不存在,则创建它
  • 如果记录存在,查找 IP,如果找到,更新评级
  • 如果记录存在但 IP 不存在,则插入新的评级

  • 作品:
    db.collection('ratings').findOne({ "refid":refid }).then(function(vote) {  
    if (vote == null) {
    newrating = {refid: refid, votes: [{ ip: ip, rating: rating }]};
    db.collection('ratings').save(newrating);
    } else {
    db.collection('ratings').findOne({ "refid":refid, "votes.ip":ip }).then(function(rate) {
    if (rate != null) {
    db.collection('ratings').update(
    { refid: refid, "votes.ip" : ip },
    { $set: { "votes.$.rating" : rating } }
    )
    } else {
    db.collection('ratings').update({"refid":refid,"votes.ip" : {$ne : ip }},
    { $push: { votes: { "ip" : ip, "rating" : rating, }}}
    )
    }
    })
    }
    })

    最佳答案

    插入一个不存在的文档是通过 upsert 完成的,如果你想更新一个有条件的嵌入文档,你需要 $ 位置运算符。因此,您需要在查询中同时使用两者来实现上述功能。
    但是现在 mongodb 不支持使用 $ 位置运算符进行更新插入

    Do not use the positional operator $ with upsert operations because,inserts will use the $ as a field name in the inserted document.


    所以你想要的东西现在不可能在一个查询中完成,或者你可以在两个查询中完成。
    第一的
    db.collection('ratings').update(
    {"refid":refid, "votes.ip": ip},
    {
    $set: { "votes.$.rating":rating }
    }
    )
    它返回更新的文档数,如果是 1 就可以了,如果是 0 则需要推送新记录。
    db.collection('ratings').update( { "refid":refid, "votes.ip":{$ne: ip}},
    {$push: { votes: { "ip":ip , "rating":rating }}
    })
    还有用于位置运算符和更新插入的 jira 票,如果您希望在 mongodb 中使用此功能,请为此问题投票。以下是问题链接
    https://jira.mongodb.org/browse/SERVER-3326
    ( 编辑 :jira 票在 2019 年 6 月以 Won't Do 关闭)

    关于node.js - 如果存在则更新 MongoDB 中的嵌套对象,否则添加它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39781173/

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