mahemoff mahemoff - 4 months ago 12
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.


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.