在更新select器中使用$ in时,Upsert Multiple Documents

我正在写一个程序,将采取一些string,如

var mywords = ["cat", "dog", "fish"] 

并将其插入MongoDb集合(称为“单词”集合)。 我想保留每个单词被插入到集合中的次数。 有些词可能已经在collections中,有些则没有。

这工作:

 var my_func = function(mywords) { //Get connection to db... mywords.forEach(function(word) { collection.update({name: word}, {$inc: {count: 1}}, {upsert: true}); }); } 

真棒。 所以现在如果{name:dog,count:3}是集合中唯一的文档,我运行my_func([“cat”,“dog”,“fish”]),那么集合现在将包含:

 {name: dog, count: 4, _id: blah} {name: cat, count: 1, _id: blah} {name: fish, count: 1, _id: blah} 

这正是我想要的,除非我想在一个更新中完成这一切,即。 不在forEach内。 我试过这个:

 var broken_func = function(mywords) { //Get connection to db... collection.update({name: {$in : {mywords}}, {$inc: {count: 1}}, {upsert: true, multi:true}); } 

但是,如果我从包含{name:dog,count:3}的相同集合开始并运行my_func([“cat”,“dog”,“fish”]),我的集合看起来像这样:

 {name: dog, count: 3} {count: 1} 

我希望MongoDb匹配文档的名称字段与mywords数组中的任何string,并增加该文档的计数字段。 如果没有文档名称字段与我的string中的某个string相同,请创build一个文档{name:“stringFrom_mywords”,count:1}。

我想做什么,怎样才能达到我想要的行为? 我觉得使用forEach并做单独的更新效率不高。 如果您发现有用的信息,我碰巧使用node.js MongoDb驱动程序。 我知道我的问题类似于这个ruby问题与MongoDb的Upsert多个logging

虽然可以使用upsert和multi标志运行更新,但不会达到所需的效果。 您将需要运行三个单独的upsert命令,就像您使用forEach示例一样。

如果您希望将此function添加到MongoDB的未来版本中,请随时在SERVER项目中打开Jira票证。