Moped: get id after insert

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

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

I try to get the "_id" of the document after pasting with 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 to get identifier using Moped?

Update:

I am also trying to use safe mode, but it does not 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 
+6
source share
2 answers

From this problem :

It would be nice, but, unfortunately, Mongo does not give us anything back when inserting (since it works and is forgotten), and when it is in safe mode it still does not return the identifier if it generated it on the server. So for us there really is no way to do this. if that was not the main feature in MongoDB.

The best thing would be to generate an identifier before inserting the document:

 document = { _id: Moped::BSON::ObjectId.new, name: "example" } id = document[:_id] 
0
source

After inserting / saving, the returned object will have the inserted_id property, which is 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 
+14
source

Source: https://habr.com/ru/post/983390/


All Articles