請問下,我有個使用者---》多個地址
我目前把地址用內嵌文檔放入用戶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;
}