【问题标题】:How do I merge into an existing unique id in MongoDB with NodeJS?如何使用 NodeJS 合并到 MongoDB 中现有的唯一 ID?
【发布时间】:2020-07-20 06:59:56
【问题描述】:

当我插入一个具有重复唯一 ID 的新条目时,我想对文档字段求和。这是我目前所拥有的:

MongoClient.connect(process.env.MONGODB_URI || process.env.DB_CONNECTION, { useUnifiedTopology: true, useNewUrlParser: true }, function (err, db) {
            if (err) throw err;
            const dbo = db.db("mydb");
            const messageTable = dbo.collection("comments");
            for(var key in words){
                let myobj = 
                [{ 
                    _id: key,
                    frequency: words[key]
                }];
                messageTable.insertMany(myobj, function(err, res){
                    if (err) throw err;
                    console.log("documents inserted");
                });
                messageTable.aggregate([
                    { $match: { _id: key } },
                    {
                      $group: {
                        _id: key, 
                        total: {
                          $sum: "$frequency"
                        }
                      }
                    },
                    { $merge: { into: "comments", whenMatched: "replace" } }
                ]);
            }
        })

通过阅读文档,如果键已经作为唯一 ID 存在,我尝试使用聚合方法来合并新条目。这目前不起作用。如何使用 NodeJS 合并 MongoDB 中的重复文档?

【问题讨论】:

  • 您可以使用输入/示例现有文档和所需的 o/p 编辑此问题吗?
  • @whoami 很抱歉我是个初学者,我不知道这意味着什么。
  • 嗨@TDonnally。只是为了澄清一些事情;为什么您使用insertMany 而不是insert,因为您只插入一个对象?另外,您那里的聚合只是为了避免具有相同_id的重复cmets对吗?
  • 是的,聚合是为了避免将 cmets 存储在我的数据库中两次。我使用了 InsertMany,因为当时 InsertOne 不工作。
  • 我打算建议您发布的答案。不错。

标签: javascript node.js mongodb express


【解决方案1】:

通过阅读文档并在 reddit 用户的帮助下,我找到了一种方法。如果有人想做类似的事情,这是最简单的方法:

messageTable.findOneAndUpdate({ "_id" : key },{$set: { "_id" : key}, $inc : { "frequency" : words[key] }},{upsert: true}).then(
                    console.log("document updated or inserted")
                )

使用此方法,第一个参数是您的查询,第二个参数更改第一个匹配项,在我的情况下增加频率字段,第三个是该方法的选项。 upsert 选项的默认值为 false,但如果为 true,则如果新文档尚不存在,则会创建一个新文档。如果您想了解更多信息,可以查找信息here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-24
    • 1970-01-01
    • 1970-01-01
    • 2021-01-13
    • 1970-01-01
    • 1970-01-01
    • 2015-07-13
    相关资源
    最近更新 更多