Multiplying multiple documents when using $ in in the selector updates

I am writing a procedure that will take an array of strings, for example

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

and activate them in the MongoDb collection (called the "word" assembly). I would like to count how many times each word has been inserted into the collection. It is possible that some of the words are already in the collection, and some are not.

It works:

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

Tall. So, if {name: dog, count: 3} was the only document in the collection, and I run my_func (["cat", "dog", "fish"]), then the collection will now contain:

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

This is exactly what I want, except that I would like to do it in just one update, i.e. not within forEach. I tried this:

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

However, if I start with the same collection that contains only {name: dog, count: 3} and runs my_func (["cat", "dog", "fish"]), my collection looks like this:

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

I want MongoDb to match the document name field with any string in the mywords array and increment the count field of this document. If mywords does not have a document name field equal to some string, create a document {name: "stringFrom_mywords", count: 1}.

I want to do what I want, and how can I achieve what I want? I believe that using forEach and doing individual updates is inefficient. I am using the node.js MongoDb driver if you find this information useful. I know my problem is similar to this ruby ​​question Multiply multiple entries with MongoDb

+4
source share
1 answer

While you can start the update using both upsert and several flags, it will not have the desired effect. You will need to run three upsert commands, as you do with your forEach example.

If you want this feature to be added to a future MongoDB translation, feel free to open a Jira ticket in the SERVER project.

+1
source

All Articles