Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a variable as a field name in mongodb-native findAndModify?

In this code that uses the mongodb-native driver I'd like to increase the value of the field which I specify in a separate variable. The problem is that the field name in the $inc clause will be 'variable' in this case, not the contents of the variable. In the query part the variable selected works as expected and finds the correct id.

var selected = 'id_of_the_selected_one';
var variable = 'some_string';
collection.findAndModify(
     {_id : selected}, 
     {},
     {$inc : {variable : 1}},
     {new : true, upsert : true},
     function(err, autoincrement) { /* ... */ }
);

How should I do it so that instead of the word 'variable' there will be the contents of the variable?

like image 759
Timo Albert Avatar asked Jun 21 '12 08:06

Timo Albert


People also ask

How do I use findAndModify in MongoDB?

MongoDB – FindAndModify() Method. The findAndModify() method modifies and return a single document that matches the given criteria. By default, this method returns a pre-modification document. To return the document with the modifications made on the update, use the new option and set its value to true.

Which option should be used with findAndModify () command to return the modified document instead of the pre modification document?

Definition. The findAndModify command modifies and returns a single document. By default, the returned document does not include the modifications made on the update. To return the document with the modifications made on the update, use the new option.

Is MongoDB findAndModify Atomic?

A findAndModify operation on a document is atomic: if the find condition matches a document, the update is performed on that document. Concurrent queries and additional updates on that document are not affected until the current update is complete.

What is new true in MongoDB?

If new is true : the modified document if the query returns a match; the inserted document if upsert: true and no document matches the query; otherwise, null .


1 Answers

Set the key of another variable to its value and pass that as an object. Note of action:

var selected = 'id_of_the_selected_one';
var variable = 'some_string';
var action = {};
action[variable] = 1; // the value

collection.findAndModify(
    {_id : selected}, 
    {}, 
    {$inc : action}, 
    {new : true, upsert : true}, 
    function(err, autoincrement) { /* ... */ }
); // Same as {$inc: {'some_string': 1} }
like image 185
Menztrual Avatar answered Oct 08 '22 15:10

Menztrual