mahemoff mahemoff - 1 year ago 81
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
? 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 Source

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

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

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