请问下,我有个用户---》多个地址
我目前把地址用内嵌文档放入用户collection,可是如果要修改地址,内嵌文档没有id怎么办? 内嵌文档怎么实现自增id?
过去多啦不再A梦2017-04-27 09:04:49
It is recommended to use uuid. To implement auto-incrementing ID, you need to manually maintain and write an auto-incrementing function in your own program. It is also more troublesome. As long as it is unique, it does not have to be auto-incrementing
迷茫2017-04-27 09:04:49
There are two methods to implement self-increasing ID in mongodb:
counter collection
db.counters.insert(
{
_id: "userid",
seq: 0
}
)
function getNextSequence(name) {
var ret = db.counters.findAndModify(
{
query: { _id: name },
update: { $inc: { seq: 1 } },
new: true
}
);
return ret.seq;
}
db.users.insert(
{
_id: getNextSequence("userid"),
name: "Sarah C."
}
)
db.users.insert(
{
_id: getNextSequence("userid"),
name: "Bob D."
}
)
Use findAndModify()
function getNextSequence(name) {
var ret = db.counters.findAndModify(
{
query: { _id: name },
update: { $inc: { seq: 1 } },
new: true,
upsert: true
}
);
return ret.seq;
}