mongodb,一对多,内嵌文档问题
天蓬老师
天蓬老师 2017-04-27 09:02:49
0
2
580

请问下,我有个用户---》多个地址
我目前把地址用内嵌文档放入用户collection,可是如果要修改地址,内嵌文档没有id怎么办? 内嵌文档怎么实现自增id?

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(2)
过去多啦不再A梦

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

迷茫

There are two methods to implement self-increasing ID in mongodb:

  1. 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."
   }
)
  1. Use findAndModify()

function getNextSequence(name) {
   var ret = db.counters.findAndModify(
          {
            query: { _id: name },
            update: { $inc: { seq: 1 } },
            new: true,
            upsert: true
          }
   );

   return ret.seq;
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template