【发布时间】: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