Excluding ID field doesn’t work with FindAndModify

While playing with incremental IDs with Mongo DB the other day, I stumbled across a bug in mongodb.

Consider the following command:

db.sequence.findAndModify({ 
     query: {"_id": "customer"}, 
     update : {$inc : {"seq":1}}, 
     fields:{"_id":0}, 
     upsert:true, 
     new:true})

Notice the fields:{"_id":0}, part (highlighted)

According to the documentation, this should prevent the id from being returned, however when I try and execute this command, I get this error:

Uncaught exception: findAndModifyFailed failed: "exception: assertion c:\\builds\laves\\mongo\\windows_64bit_v1.6\\mongo\\db\\../bson/bsonbjbuilder.h:115"

image

I opened a ticket with their issue tracking system (Jira)

After a day or so, I had a response that this was caused by a limitation to how FindAndModify was implemented.

Luckily, they’re planning on re-implementing this feature (see this ticket) which should remove this restriction.

In the meantime, the method of auto-incrementing ID’s described in my previous post will still work, but it will return the _id as well.

In a future release of mongodb, we’ll be able to strip this out, and make it even speedier!

One response to “Excluding ID field doesn’t work with FindAndModify”

Leave a Reply

Your email address will not be published. Required fields are marked *