I need to create human readable id in Mongo like (1,2,3,4,...,n+1) for documents in collection . Is there any way to create they by native mongo tools or I must create they in program's logic. p.s I use mongoengine as ORM.
Asked
Active
Viewed 4,103 times
1 Answers
5
http://www.mongodb.org/display/DOCS/Object+IDs#ObjectIDs-SequenceNumbers
Traditional databases often use increasing sequence numbers for primary keys. In MongoDB, the preferred approach is to use Object IDs instead. The concept is that in a very large cluster of machines, it is easier to create an object ID than have global, uniformly increasing sequence numbers.
However, sometimes you may want a sequence number. You can do this by creating "counter" documents and using the findAndModify Command.
Code sample (from attached link):
function counter(name) {
var ret = db.counters.findAndModify({query:{_id:name}, update:{$inc : {next:1}}, "new":true, upsert:true});
// ret == { "_id" : "users", "next" : 1 }
return ret.next;
}
db.users.insert({_id:counter("users"), name:"Sarah C."}) // _id : 1
db.users.insert({_id:counter("users"), name:"Bob D."}) // _id : 2
Check also answers to this question

Community
- 1
- 1

maialithar
- 3,065
- 5
- 27
- 44
-
Great, I'am lazy log and can't into official documentations )) – Denis Mar 30 '12 at 07:20