How can I create unique IDs for embedded documents in MongoDB?

前端 未结 6 546
北海茫月
北海茫月 2021-01-30 13:37

So I need to reference particular subdocuments uniquely from items in my collection. For instance:

User = {
    \'name\': \'jim\',
    \'documents: [
        {\         


        
6条回答
  •  一整个雨季
    2021-01-30 14:15

    All drivers have functionality for generating ObjectIds.

    In the shell you just do new ObjectId():

    > db.test.insert({x:new ObjectId()});
    > db.test.find();
    { "_id" : ObjectId("4f88592a06c05e4de90d0bc1"), "x" : ObjectId("4f88592a06c05e4de90d0bc0") }
    

    In Java it's new ObjectId() as well. See the API docs for your driver to see the specific syntax.

提交回复
热议问题