【问题标题】:Is there a way to add an incrementing id in one statement in MongoDB?有没有办法在 MongoDB 的一个语句中添加递增的 id?
【发布时间】:2020-07-17 04:21:54
【问题描述】:

所以我有一个小型数据库,它不会增长太多,我正试图从我用 python 实现的 API 中的数据库中获取一个文档,以便使用给定的文档 ID 我在D b。但是,我发现让用户从数据库中写入一个随机数有点困难。我所需要的只是一个通过设置 id 字段和自动增量来修改每个文档的函数。正如我所说,它不会增长那么多,性能也不是问题。

到目前为止,我能够做到的是:

var i = 0
db.MyCollection.update({},
                          {$set : {"new_field":1}},
                          {upsert:false,
                          multi:true}
i ++;),

我实现了设置一个 id 字段,但它为每个文档设置了相同的数字(每个文档的计数)所以假设数据库有 10 个文档,它会将 ID 设置为 10。

【问题讨论】:

    标签: python-3.x mongodb pymongo mongo-shell


    【解决方案1】:

    查找和修改操作返回更新的文档(更新之前或之后取决于 returnDocument 设置)。您可以将其与 $inc 一起使用来实现计数器。 c 是一个集合的 Ruby 示例:

    irb(main):005:0> c['foo'].insert_one(counter:true,count:1)
    => #<Mongo::Operation::Insert::Result:0x8040 documents=[{"n"=>1, "opTime"=>{"ts"=>#<BSON::Timestamp:0x00005609f260b7e0 @seconds=1594961771, @increment=2>, "t"=>1}, "electionId"=>BSON::ObjectId('7fffffff0000000000000001'), "ok"=>1.0, "$clusterTime"=>{"clusterTime"=>#<BSON::Timestamp:0x00005609f260b538 @seconds=1594961771, @increment=2>, "signature"=>{"hash"=><BSON::Binary:0x8060 type=generic data=0x0000000000000000...>, "keyId"=>0}}, "operationTime"=>#<BSON::Timestamp:0x00005609f260b290 @seconds=1594961771, @increment=2>}]>
    
    irb(main):011:0> c['foo'].find_one_and_update({counter:true},{'$inc':{count:1}})
    => {"_id"=>BSON::ObjectId('5f112f6b2c97a6281f63f575'), "counter"=>true, "count"=>1}
    irb(main):012:0> c['foo'].find_one_and_update({counter:true},{'$inc':{count:1}})
    => {"_id"=>BSON::ObjectId('5f112f6b2c97a6281f63f575'), "counter"=>true, "count"=>2}
    irb(main):013:0> c['foo'].find_one_and_update({counter:true},{'$inc':{count:1}})
    => {"_id"=>BSON::ObjectId('5f112f6b2c97a6281f63f575'), "counter"=>true, "count"=>3}
    irb(main):014:0> c['foo'].find_one_and_update({counter:true},{'$inc':{count:1}})
    => {"_id"=>BSON::ObjectId('5f112f6b2c97a6281f63f575'), "counter"=>true, "count"=>4}
    

    【讨论】:

      【解决方案2】:

      为什么不直接使用这个逻辑呢?不是通过一个查询全部更新,而是一一启动多个查询? Mongo 会很快完成,即使您的数据库中有超过 100 万个文档(根据您的说法:我有一个小数据库),因为在 _id 字段上预先建立了索引。

      这是一个 javasript 代码,但我想,你会理解它的逻辑

      let all_documents = db.MyCollection.find({});
      
      for (let i = 0; i < all_documents.length; i++) {
        db.MyCollection.update({_id: all_documents[i]._id }, {$set : {"new_field": i}}, {upsert:false})
      }
      

      【讨论】:

      • 我尝试这样做,但它不起作用,它与我对显示的查询所做的相同。它仅将 id 字段设置为 5,这是我在该特定集合中拥有的最大文档数
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-11-25
      • 1970-01-01
      • 2021-11-07
      • 2020-09-04
      • 2022-07-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多