I’ve been reading a lot recently on MongoDB and the use of incrementing an ID
This article offers an in depth look: http://shiflett.org/blog/2010/jul/auto-increment-with-mongodb
Taking this a little further, and from reading the findAndModify documentation I put together the following:
db.sequence.findAndModify({ query: {"_id": "customer"}, update : {$inc : {"seq":1}}, upsert:true, new:true})
Here is what this command does:
- Finds (or creates) the “sequence” collection
- Gets the document with id “customer”
- Increments the value of “seq” by 1
- If this document doesn’t exist, it creates it (upsert:true)
- Returns the new value of “seq”
Of course, in production, I’d shorten “seq” to just “s” or something like that, for even speedier responses!
The advantages of this are you don’t need to initialise your “sequence” collection first, or check if your document exists first. If it doesn’t exist, it will create it!
Important Note
At the time of writing, unfortunately, the whole document (ie- id and seq) is returned with this operation
According to the documentation, we should be able to specify “fields” to remove the id from the returned doc, however this doesn’t seem to work.
I have opened a ticket on MognoDB Jira for this.
See this post for more information.
Leave a Reply