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

前端 未结 6 606
北海茫月
北海茫月 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 13:59

    And this is how you can do it in python (pymongo):

    from pymongo import MongoClient
    import bson
    
    client = MongoClient('mongodb://localhost:27017/')
    db = client.test_db
    
    result=db.users.insert_one({'name': 'jim',
        'documents': [
            {'_id': bson.objectid.ObjectId(), 'title': "My document"},
            {'_id': bson.objectid.ObjectId(), 'title': "My second document!"},
        ]})
    
    print list(db.users.find({}))
    

提交回复
热议问题