[英]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
是 db 集合的貓鼬模式。
這似乎不起作用。 我輸入了一組新標簽,但沒有添加它們,也沒有增加現有標簽。
有沒有辦法處理這個而不必循環遍歷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 集合當前為空,因此不應為空。
我認為您可以在幾個查詢中完成此操作,而無需循環查詢。
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.