Mongodb查看数组中是否所有项都存在,并更新else插入
Mongodb see if all items in array exist and update else insert
我有一个mongo标签集合,当用户输入一个标签数组时,我想执行以下操作:
如果数组中存在标记,请更新计数如果阵列中不存在标签,则插入计数为0的
我目前有:
QuestionTags.update({'tag': {$in: tagArray}}, {$inc : {'count': +1} }, { upsert: true });
QuestionTags
是数据库集合的mongoose模式。
这似乎不起作用。我输入了一个新标签的数组,它们不会被添加,现有的标签也不会增加。
有没有一种方法可以在不必循环通过tagArray
并对数组中的每个项进行db调用的情况下处理此问题?
更新:将我的代码更改为此
QuestionTags.update({'tag': {$in: req.body.tags}}, {$inc : {'count': +1} }, { upsert: true, multi: true });
QuestionTags.find({'tag' :{$nin: req.body.tags}}, function(err, newTags) {
console.log("New Tags :" + newTags);
var tagArray = [];
newTags.forEach(function(tag){
var tagObj = {
tag: tag,
count: 1
}
tagArray.push(tagObj);
});
QuestionTags.collection.insert(tagArray);
});
但是,newTags
为空。QuestionTags集合当前为空,因此不应为null。
我认为您可以在几个查询中做到这一点,而无需在循环中进行查询。
1) 更新现有标签计数:您的查询有效:
QuestionTags.update({'tag': {$in: tagArray}}, {$inc : {'count': +1} },{multi: true} );
2) 查找新标签:
QuestionTags.find({},function(err, tags) {
var newTagObj = [];
// tags is originally an array of objects
// creates an array of strings (just tag name)
tags = tags.map(function(tag) {
return tag.tag;
});
// returns tags that do not exist
var newTags = tagArray.filter(function(tag) {
// The count = 1 can be done here
if (tags.indexOf(tag) < 0) {
tag.count = 1;
}
return tags.indexOf(tag) < 0;
});
// creates tag objects with a count of 1
// adds to array
// (this can be done in the previous loop)
newTags.forEach(function(tag) {
var tagObj = {
tag: tag,
count: 1
}
newTagObj.push(tagObj);
});
这将为您提供一个数据库中不存在的标签数组。
3) 在find
回调中使用2的结果插入新标签:
QuestionTags.collection.insertMany(newTagObj);
相关文章:
- 在scala或scalajs Diode中,现有类型中的任何一种都符合“;更新一个没有'还不存在”;
- 事件侦听器更新就绪在加载时未显示确认,而更新实际存在
- 如何获取数据属性中存在的现有JSON并更新它
- 检查文档是否已经存在,如果是则更新,否则创建新的Mongoose
- Mongodb查看数组中是否所有项都存在,并更新else插入
- 检查第 n 个子项是否存在,如果没有,则创建并更新
- 使用新的键,值对象(如果存在)更新多维数组或创建新的
- 更新的问题::查询选择器可能存在PhantomJS/Javascript问题
- 更新对象或创建对象(如果不存在)
- 正在尝试测试数组中是否存在项,并更新数组
- 更新shape并将新值保存在json中
- 如果存在,请更新或向对象数组添加新元素 - javascript + lodash 中的优雅方式
- 如果不存在则创建文档,否则,更新-无论哪种情况都返回文档
- 如果存在更新,则插入图片上传
- MongoDB:更新嵌套数组元素,如果不存在则插入它
- MySQL和PHP:循环遍历表,查找存在的值,如果不存在则更新,插入新值
- Javascript -是否存在具有自更新值的变量
- Highstock.js / Angular.js中的范围选择器在xAxis配置字段存在时不会更新图表
- MongoDB查找文档如果存在-更新否则-插入
- 一个JavaScript函数,用于更新多个隐藏字段,具体取决于它们是否存在