Search code examples
rubymongodbbson

Get MongoDB object size through Ruby connector


How do I get the BSON document size of a MongoDB record using the Ruby connector? For BSON::Document.new(some_hash), .size seems to return the number of keys for the document, .bson_size doesn't exist, and .data_size returns an error.


Solution

  • As of Mongo's Ruby Driver 2.0 release, BSON.serialize is removed. If you have a BSON::Document, you can transform it to a BSON::ByteBuffer by calling to_bson, and then get its size by calling length on that.

    Example:

    BSON::Document.new({a: 1}).to_bson.length
    => 12