如何检查Mongo的$ addToSet是否重复 [英] How to check if Mongo's $addToSet was a duplicate or not

查看:142
本文介绍了如何检查Mongo的$ addToSet是否重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Mongoskin + NodeJS向我的MongoDB添加新关键字.我想通知用户该条目是重复条目,但不确定如何执行此操作.

I am using Mongoskin + NodeJS to add new keywords to my MongoDB. I want to notify the user that the entry was a duplicate but not sure how to do this.

/*
* POST to addkeyword.
*/
router.post('/addkeyword', function(req, res) {
var db = req.db;
db.collection('users').update({email:"useremail@gmail.com"}, {'$addToSet': req.body }, function(err, result) {
    if (err) throw err;
    if (!err) console.log('addToSet Keyword.' );
}); 
});

结果似乎对我没有任何用处,因为它不会告诉我是否添加了关键字.

The result does not seem to be of any use to me since it doesn't tell me if the keyword was added or not.

推荐答案

至少在外壳程序中,您可以区分文档是否被修改(请参见nModified).

At least in the shell you can differentiate if the document was modified or not (see nModified).

> db.test4.update({_id:2}, {$addToSet: {tags: "xyz" }})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

> db.test4.update({_id:2}, {$addToSet: {tags: "xyz" }})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 0 })

更新节点

使用collection.update(criteria, update[[, options], callback]);时,您可以检索已修改的记录数.

When you use collection.update(criteria, update[[, options], callback]); you can retrieve the count of records that were modified.

从节点文档

From the node docs

callback 是记录更新后要运行的回调.已 两个参数,第一个是错误对象(如果发生错误), 第二个是已修改的记录数.

callback is the callback to be run after the records are updated. Has two parameters, the first is an error object (if error occured), the second is the count of records that were modified.

另一个更新

似乎至少在1.4.3版中,本机Mongo Node驱动程序的行为与所记录的不同.可以使用批量API(在Mongo 2.6中引入)解决该问题:

It seems at least in version 1.4.3 the native Mongo Node driver is not behaving as documented. It is possible to work around using the bulk API (introduced in Mongo 2.6):

var col = db.collection('test');
// Initialize the Ordered Batch
var batch = col.initializeOrderedBulkOp();
batch.find({a: 2}).upsert().updateOne({"$addToSet": {"tags": "newTag"}});
// Execute the operations
batch.execute(function(err, result) {
  if (err) throw err;
  console.log("nUpserted: ", result.nUpserted); 
  console.log("nInserted: ", result.nInserted); 
  console.log("nModified: ", result.nModified); // <- will tell if a value was added or not
  db.close();
});

这篇关于如何检查Mongo的$ addToSet是否重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆