2

The following is more of a question out of curiosity.

I'm currently running a script that updates each user in my database by pushing an ObjectID reference to into an array within the user schema.

From my understanding, there is little difference between the .update and .findAndModify commands in MongoDB. However, I receive an error when I use .findAndModify whereas .update works perfectly well.

Here's my script:

var panos = db.panos.find();
var total = 0;
while(panos.hasNext()) {
    var pano = panos.next();
    var author = db.users.findOne({ _id: pano._id});

    /* here I use the .update command */
    db.users.update(
        { _id: ObjectId(pano.author) },
        { $addToSet: { panos: pano._id }}
    );

    total++;
    print('total looked at:', total)
}

And the users are updated as expected. When I replace .users() with .findAndModify(), the following error logs in the console:

Error: findAndModifyFailed failed: {
    "ok" : 0,
    "errmsg" : "no such command: _id",
    "code" : 59,
    "bad cmd" : {
        "_id" : ObjectId("5616dd0a35ea7932106b7c57"),
        "findandmodify" : "users"
    }
}

It looks like the _id query is giving a problem, but I can't wrap my head around why. I've tried replacing ObjectId(pano.author) with just pano.author but to no avail.

TL;DR: .update works where .findAndModify doesn't

Community
  • 1
  • 1
robinnnnn
  • 1,675
  • 4
  • 17
  • 32
  • Atomicity is a more relevant difference between them two. See http://stackoverflow.com/questions/10778493/whats-the-difference-between-findandmodify-and-update-in-mongodb?rq=1 – Peter Jul 20 '16 at 11:46

1 Answers1

3

In the shell, findAndModify takes a single parameter object rather than separate parameters like update, so you need to call it as:

db.users.findAndModify({
    query: { _id: ObjectId(pano.author) },
    update: { $addToSet: { panos: pano._id }}
});
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471