簡體   English   中英

如何使用 NodeJS 合並到 MongoDB 中現有的唯一 ID?

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

當我插入具有重復唯一 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 中的重復文檔?

通過閱讀文檔並在 reddit 用戶的幫助下,我找到了一種方法。 如果有人想做類似的事情,這是最簡單的方法:

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

使用此方法,第一個參數是您的查詢,第二個更改第一個匹配項,在我的情況下增加頻率字段,第三個是該方法的選項。 upsert 選項的默認值為 false,但當 true 時,如果一個新文檔不存在,則會創建一個新文檔。 如果您想了解更多信息,可以在這里找到信息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM