为什么mongo ruby​​驱动程序在第一次插入后向数据哈希添加_id键?

时间:2013-10-16 20:40:24

标签: ruby mongodb

我正在尝试将此哈希插入我的数据库:

a = {"name" => "Apple"}

所以我使用IRB连接。

irb(main):001:0> require 'mongo'
=> true
irb(main):002:0> include Mongo
=> Object
irb(main):003:0> client =  MongoClient.new("localhost",27017).db("sample").collection("stack")
=> #<Mongo::Collection:0x9ee5c74 @name="stack", @db=#<Mongo::DB:0x9ee5ee0 @name="sample", @connection

现在这是我遇到问题的地方:

irb(main):004:0> client.count
=> 0
irb(main):005:0> a = {"name" => "Apples"}
=> {"name"=>"Apples"}

到目前为止工作正常。插入成功。

> db.stack.find().pretty()
{ "_id" : ObjectId("525ee9d79fd1b325a4000001"), "name" : "Apples" }

在红宝石方面工作:

irb(main):005:0> a = {"name" => "Apples"}
=> {"name"=>"Apples"}
irb(main):006:0> client.insert(a)
=> BSON::ObjectId('525ee9d79fd1b325a4000001')

如果我尝试再次添加相同的哈希值,则会出现错误

irb(main):007:0> client.insert(a)
Mongo::OperationFailure: 11000: E11000 duplicate key error index: sample.stack.$_id_  dup key: { : ObjectId('525ee9d79fd1b325a4000001') }
    from /var/lib/gems/1.9.1/gems/mongo-1.9.2/lib/mongo/networking.rb:103:in `send_message_with_gle'
    from /var/lib/gems/1.9.1/gems/mongo-1.9.2/lib/mongo/collection.rb:1121:in `block in send_insert_message'
    from /var/lib/gems/1.9.1/gems/mongo-1.9.2/lib/mongo/util/logging.rb:55:in `block in instrument'
    from /var/lib/gems/1.9.1/gems/mongo-1.9.2/lib/mongo/util/logging.rb:20:in `instrument'
    from /var/lib/gems/1.9.1/gems/mongo-1.9.2/lib/mongo/util/logging.rb:54:in `instrument'
    from /var/lib/gems/1.9.1/gems/mongo-1.9.2/lib/mongo/collection.rb:1119:in `send_insert_message'
    from /var/lib/gems/1.9.1/gems/mongo-1.9.2/lib/mongo/collection.rb:1111:in `insert_batch'
    from /var/lib/gems/1.9.1/gems/mongo-1.9.2/lib/mongo/collection.rb:1169:in `insert_documents'
    from /var/lib/gems/1.9.1/gems/mongo-1.9.2/lib/mongo/collection.rb:389:in `insert'
    from (irb):7
    from /usr/bin/irb:12:in `<main>'

什么?我的哈希已经改变了

irb(main):008:0> a
=> {"name"=>"Apples", :_id=>BSON::ObjectId('525ee9d79fd1b325a4000001')}

已添加_id字段,因此如果要进行批处理插入,我将如何处理它?<​​/ p>

为什么将_id添加到原始哈希值时会出现默认行为,如何解决此问题

经过一番搜索,似乎这是BSON Gem中的行为。

[http://api.mongodb.org/ruby/current/BSON/ObjectId.html] [1]

+ (BSON::ObjectId, Object) create_pk(doc) 



 File 'lib/bson/types/object_id.rb', line 91

def self.create_pk(doc)
  doc.has_key?(:_id) || doc.has_key?('_id') ? doc : doc.merge!(:_id => self.new)
end

一个人怎么会这样:

a = {"name" => "Blue"}
2.times {client.insert(a)}

1 个答案:

答案 0 :(得分:1)

如果你真的不希望它添加一个ID,插入它时可能只是dup对象?

a = { "name" => "Blue" }
2.times { client.insert(a.dup) }