search

Home  >  Q&A  >  body text

mongodb,一对多,内嵌文档问题

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

天蓬老师天蓬老师2792 days ago581

reply all(2)I'll reply

  • 过去多啦不再A梦

    过去多啦不再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

    reply
    0
  • 迷茫

    迷茫2017-04-27 09:04:49

    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;
    }

    reply
    0
  • Cancelreply