Heim > Fragen und Antworten > Hauptteil
请问下,我有个用户---》多个地址
我目前把地址用内嵌文档放入用户collection,可是如果要修改地址,内嵌文档没有id怎么办? 内嵌文档怎么实现自增id?
迷茫2017-04-27 09:04:49
在mongodb中实现自增长id,有2种方法:
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."
}
)
用findAndModify()
function getNextSequence(name) {
var ret = db.counters.findAndModify(
{
query: { _id: name },
update: { $inc: { seq: 1 } },
new: true,
upsert: true
}
);
return ret.seq;
}