Question

I am running the below query and It does not work. When I run the query part in mongo UI, it returns me expected result. I am using UMongo. But it does not update the document as expected.

db.system.js.save ({    
_id:"script_1",
value: function() {

    print("in function>>");             

    db.data.find({"$and": 
        [{"title":{$regex : '.*Green Red.*', $options : 's'}},
         {"editor.key": {"$in": ["74014","45339"]}}, {"types" : {"$in": ["Notes"]}}]}).forEach(
          function(docMatch){
                  print("Matching document found");
                      db.data.update(docMatch, 
                              {$set:{"editor.key": "05335","editor.value": "editor1", 
                          "editor.email": "editor1@gmail.com"}
                    }, false, true);
      }
    );

    db.data.reIndex();
    }
 });

 db.eval("script_1()");  

I do see "Matching document found" in the mongo logs but does not update. Shows below message too in the logs.

     Thu Sep 19 11:03:43 [conn1279] warning: ClientCursor::yield can't unlock b/c of recursive lock ns             

Thanks for you help !

Was it helpful?

Solution

I'm not sure exactly what the problem is without having your data and being able to run your query. However, there are lots of issues with this code:

  • Why save this as a script and then call db.eval() rather than running your update directly?
  • Why do you need to reindex?
  • You do not need the $and operator in your query.
  • You do not need separate calls to find and update; in fact, one call to update with the multiupdate flag set to true should suffice.
  • The $in is unnecessary in {"$in": ["Notes"]}.
  • Using {$regex: '.Green Red.'} could potentially be slow. The $regex operator cannot use an index in this case because an index can only be used to match a prefix. See the last paragraph here: http://docs.mongodb.org/manual/reference/operator/regex/.

If this is code generated by UMongo, I recommend moving away from UMongo and working with the officially supported mongo shell.

In order to fix your call to update, try running something like this in the mongo shell:

db.data.update(
  {
    "title": {$regex : '.*Green Red.*', $options : 's'},
    "editor.key": {"$in": ["74014","45339"]},
    "types" : "Notes"
  },
  {
    $set: {
            "editor.key": "05335",
            "editor.value": "editor1",
            "editor.email": "editor1@gmail.com"
          }
  },
  false,
  true
);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top