简体   繁体   English

如何使用 NodeJS 合并到 MongoDB 中现有的唯一 ID?

[英]How do I merge into an existing unique id in MongoDB with NodeJS?

I want to sum a documents field when I insert a new entry that has a duplicate unique id.当我插入具有重复唯一 ID 的新条目时,我想对文档字段求和。 This is what I have so far:这是我到目前为止所拥有的:

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

From reading the docs I tried to use the aggregate method to merge new entries if the key already exists as a unique id.通过阅读文档,如果密钥已经作为唯一 ID 存在,我尝试使用聚合方法合并新条目。 This is not currently working.这目前不起作用。 How would I merge duplicate documents in my MongoDB using NodeJS?如何使用 NodeJS 合并 MongoDB 中的重复文档?

I have figured out a way to do this by reading the docs and with the help of a reddit user.通过阅读文档并在 reddit 用户的帮助下,我找到了一种方法。 If anyone wants to do something similar this is the easiest method:如果有人想做类似的事情,这是最简单的方法:

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

With this method the first argument is your query, the second changes the first match which in my case increments the frequency field, and the third are options for the method.使用此方法,第一个参数是您的查询,第二个更改第一个匹配项,在我的情况下增加频率字段,第三个是该方法的选项。 The upsert option has a default value of false but when true creates a new document if one does not already exist. upsert 选项的默认值为 false,但当 true 时,如果一个新文档不存在,则会创建一个新文档。 If you wish to read more you can find info here如果您想了解更多信息,可以在这里找到信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM