【问题标题】:Mongo - Are the ObjectIds of duplicate documents different?Mongo - 重复文档的 ObjectId 是否不同?
【发布时间】:2019-07-27 10:22:56
【问题描述】:

所以我试图了解如何在 Mongo 中创建 ObjectId,我发现 this 页面描述了它:

a 4-byte value representing the seconds since the Unix epoch,
a 5-byte random value, and
a 3-byte counter, starting with a random value.

由于时间戳,这是否意味着即使将具有相同确切内容的文档插入到数据库中也会被分配两个不同的“ObjectId”?

即。这?

db.Collection.insert({'field one' : 'example'} # ObjectID = X
db.Collection.insert({'field one' : 'example'} # ObjectID = Y 

【问题讨论】:

    标签: mongodb pymongo


    【解决方案1】:

    插入文档的内容不会影响生成的 ObjectId。即使在一秒钟内生成两个ObjectId,在一台机器上和一个进程内,它们也必须根据3字节计数器不同,以随机值开头。我测试了您的示例并获得了 ObjectIds,它仅在属于此计数器的最后一位不同:

    import pymongo
    from pprint import pprint
    
    client = pymongo.MongoClient()
    db = client.db
    collection = db.collection
    
    collection.insert_one({'field one' : 'example'}) # ObjectID = X
    collection.insert_one({'field one' : 'example'}) # ObjectID = Y 
    
    pprint(list(collection.find()))
    
    # output:
    # [{'_id': ObjectId('5c7ee99688f00210d72f224e'), 'field one': 'example'},
    #  {'_id': ObjectId('5c7ee99688f00210d72f224f'), 'field one': 'example'}]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-31
      • 2012-07-30
      • 2014-10-18
      • 2023-03-20
      • 2017-06-22
      • 2018-11-11
      • 2020-07-16
      相关资源
      最近更新 更多