6

When I use mongo-ruby-driver and I insert new document it returns generated '_id':

db = MongoClient.new('127.0.0.1', '27017').db('ruby-mongo-examples')
id = db['test'].insert({name: 'example'})

# BSON::ObjectId('54f88b01ab8bae12b2000001')

I'm trying to get the '_id' of a document after doing an insertion using Moped:

db = Moped::Session.new(['127.0.0.1:27017'])
db.use('ruby-mongo-examples')
id = db['coll'].insert({name: 'example'})

# {"connectionId"=>15, "n"=>0, "syncMillis"=>0, "writtenTo"=>nil, "err"=>nil, "ok"=>1.0}

How I get the id using Moped?

Update:

I also try use safe mode but it doesn't work:

db = Moped::Session.new(['127.0.0.1:27017'])
db.use('ruby-mongo-examples')

db.with(safe: true) do |safe|
  id = safe['coll'].insert({name: 'example'})

  # {"connectionId"=>5, "n"=>0, "syncMillis"=>0, "writtenTo"=>nil, "err"=>nil, "ok"=>1.0}
end
rjurado01
  • 5,337
  • 3
  • 36
  • 45
  • 1
    You can get it in the response if you do a [safe insert](http://mongoid.org/en/moped/) or generate it before the insert like `document = { _id: Moped::BSON::ObjectId.new, name: "example" } id = document[:_id]` – chridam Mar 05 '15 at 18:51
  • 1
    I found this issue: https://github.com/mongoid/moped/issues/129. It seems that the only way is generte id with BSON::ObjectId.new and use it. Thanks @chridam. – rjurado01 Mar 06 '15 at 11:43
  • I think @hamster_ham's answer is more appropriate than mine, your call to accept it. – chridam Aug 22 '16 at 10:07

2 Answers2

15

After inserting/saving, the returned object will have a property inserted_id which is a BSON::ObjectId:

# I'm using insert_one
result = safe['coll'].insert_one({name: 'example'})   
result.methods.sort        # see list of methods/properties
result.inserted_id
result.inserted_id.to_s    # convert to string
conradkleinespel
  • 6,560
  • 10
  • 51
  • 87
hamster ham
  • 729
  • 8
  • 8
0

From this issue:

It would be nice, but unfortunately Mongo doesn't give us anything back when inserting (since it's fire and forget), and when in safe mode it still doesn't give the id back if it generated it on the server. So there really isn't any possible way for us to do this unless it was a core feature in MongoDB.

Your best bet would be to generate the id before inserting the document:

document = { _id: Moped::BSON::ObjectId.new, name: "example" } 
id = document[:_id]
chridam
  • 100,957
  • 23
  • 236
  • 235