You can do this, every time I create a new user for example he does the auto increment of _id. Starting from 1 and going up to the number of users
You can do this, every time I create a new user for example he does the auto increment of _id. Starting from 1 and going up to the number of users
Yes, following the example of the documentation ( create-an-auto- incrementing-field ) would look something like this:
1 - Enter in the counter collection the initial value for the field:
db.counters.insert(
{
_id: "userid",
seq: 0
}
)
2 - Create a getNextSequence
function that accepts a string name. The function uses the findAndModify()
method to atomically increment the value seq
and return this new value:
function getNextSequence(name) {
var ret = db.counters.findAndModify(
{
query: { _id: name },
update: { $inc: { seq: 1 } },
new: true
}
);
return ret.seq;
}
3 - Use this getNextSequence()
function during insertion.
db.users.insert(
{
_id: getNextSequence("userid"),
name: "Sarah C."
}
)
db.users.insert(
{
_id: getNextSequence("userid"),
name: "Bob D."
}
)
For more information, see the documentation.
The MongoDB documentation itself has an example and shows you how to do it. Even they say that the method used is more recommended for _id, just what you need. Take a look at HERE .