mahemoff mahemoff - 2 months ago 8
Ruby Question

Ruby Mongo - Get back ID after insert

For example:

result = collection.insert_one({ name: 'test' })


Now how do I get back the ID of the new document, assuming it was successfully inserted? Is there any way to get it from
result
? Seems to be possible with some languages/drivers but can't see how to do it with default Ruby Mongo driver, unless I ran a query afterwards.

Answer

You can first generate the id and then send the insert with the id included.

oid = BSON::ObjectId.new
result = collection.insert_one({ _id: oid, name: 'test'})

This way you have all the info already and don't need to get anything back.

Comments