0

I am trying to insert this hash into my database:

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

So I connect using 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

Now this is where I run into an issue:

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

Works fine so far. Insert was successful.

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

Works on the ruby side:

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

Here is where the error occurs, if I try to add the same hash again

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>'

What? My Hash has changed

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

_id field has been added to it, so how will I handle batch Inserts if this is the way its going to be done?

Why is there default behavior to add the _id to my original hash, and how do I get around it

After some searching, it seems this is behaviour in the 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

How would a person so things like:

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

1 回答 1

1

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

a = { "name" => "Blue" }
2.times { client.insert(a.dup) }
于 2013-10-16T21:16:53.523 回答