bson vs mongodb vs bson-ext
MongoDB Data Serialization Libraries Comparison
1 Year
bsonmongodbbson-extSimilar Packages:
What's MongoDB Data Serialization Libraries?

These packages are essential for working with BSON (Binary JSON), the data format used by MongoDB. They facilitate the serialization and deserialization of data between JavaScript objects and BSON format, which is crucial for efficient data storage and retrieval in MongoDB databases. Understanding the differences between these packages helps developers choose the right tool for their specific needs in Node.js applications that interact with MongoDB.

Package Weekly Downloads Trend
Github Stars Ranking
Stat Detail
Package
Downloads
Stars
Size
Issues
Publish
License
bson7,131,3821,1762.41 MB57 days agoApache-2.0
mongodb6,828,16310,1003.77 MB246 days agoApache-2.0
bson-ext2,93843134 kB17-Apache-2.0
Feature Comparison: bson vs mongodb vs bson-ext

Performance

  • bson:

    The bson package is implemented in pure JavaScript, which may lead to slower performance for large datasets compared to native implementations. However, it is sufficient for many applications that do not require extreme performance optimizations.

  • mongodb:

    The mongodb package integrates BSON handling within its driver, providing a balanced performance for typical database operations. While it may not match the raw speed of bson-ext, it offers a good compromise between performance and ease of use.

  • bson-ext:

    The bson-ext package offers significant performance improvements by utilizing native C++ bindings. This results in faster serialization and deserialization processes, making it suitable for applications that handle large volumes of data or require low-latency operations.

Ease of Use

  • bson:

    The bson package is easy to use and integrates seamlessly with JavaScript applications. Its API is straightforward, making it accessible for developers who need basic BSON functionality without additional complexity.

  • mongodb:

    The mongodb package is designed to be user-friendly, providing a comprehensive API that abstracts many complexities of database interactions. It is well-documented, making it easy for developers to get started with MongoDB.

  • bson-ext:

    The bson-ext package may require additional setup due to its native bindings, which can complicate installation on certain platforms. However, once set up, it provides a familiar API for developers already accustomed to the bson package.

Compatibility

  • bson:

    The bson package is compatible with any JavaScript environment, including Node.js and browsers, making it versatile for various applications.

  • mongodb:

    The mongodb package is specifically tailored for Node.js, providing a robust interface for connecting to and interacting with MongoDB databases. It is not intended for use in browser environments.

  • bson-ext:

    The bson-ext package is primarily designed for Node.js environments due to its native bindings, which may not be suitable for browser-based applications.

Functionality

  • bson:

    The bson package focuses solely on BSON serialization and deserialization, providing essential functions to convert between JavaScript objects and BSON format.

  • mongodb:

    The mongodb package offers a full-fledged driver for MongoDB, including BSON handling, connection management, and a wide range of database operations, making it the most feature-rich option for developers.

  • bson-ext:

    The bson-ext package extends the functionality of the bson package by providing faster serialization and deserialization methods, but it does not add new features beyond BSON handling.

Community and Support

  • bson:

    The bson package has a strong community and is widely used in various projects, ensuring good support and regular updates.

  • mongodb:

    The mongodb package is the official driver for MongoDB, backed by MongoDB Inc., ensuring extensive documentation, community support, and regular updates.

  • bson-ext:

    The bson-ext package, while less commonly used than bson, has a dedicated user base and is maintained for performance-focused applications.

How to Choose: bson vs mongodb vs bson-ext
  • bson:

    Choose bson if you need a lightweight and straightforward library for BSON serialization and deserialization without additional dependencies. It is suitable for basic use cases where performance is essential and you do not require advanced features.

  • mongodb:

    Choose mongodb if you need a comprehensive driver for interacting with MongoDB databases. This package includes built-in BSON handling and provides a complete set of features for database operations, including connection management, CRUD operations, and advanced querying capabilities.

  • bson-ext:

    Choose bson-ext if you need enhanced performance and are working with large datasets. This package provides a native C++ binding for BSON serialization, which can significantly speed up the process compared to the pure JavaScript bson package. It is ideal for applications that require high throughput and efficiency.

README for bson

BSON parser

BSON is short for "Binary JSON," and is the binary-encoded serialization of JSON-like documents. You can learn more about it in the specification.

Table of Contents

Release Integrity

Releases are created automatically and signed using the Node team's GPG key. This applies to the git tag as well as all release packages provided as part of a GitHub release. To verify the provided packages, download the key and import it using gpg:

gpg --import node-driver.asc

The GitHub release contains a detached signature file for the NPM package (named bson-X.Y.Z.tgz.sig).

The following command returns the link npm package.

npm view bson@vX.Y.Z dist.tarball 

Using the result of the above command, a curl command can return the official npm package for the release.

To verify the integrity of the downloaded package, run the following command:

gpg --verify bson-X.Y.Z.tgz.sig bson-X.Y.Z.tgz

[!Note] No verification is done when using npm to install the package. The contents of the Github tarball and npm's tarball are identical.

Bugs / Feature Requests

Think you've found a bug? Want to see a new feature in bson? Please open a case in our issue management tool, JIRA:

  1. Create an account and login: jira.mongodb.org
  2. Navigate to the NODE project: jira.mongodb.org/browse/NODE
  3. Click Create Issue - Please provide as much information as possible about the issue and how to reproduce it.

Bug reports in JIRA for the NODE driver project are public.

Usage

To build a new version perform the following operations:

npm install
npm run build

Node.js or Bundling Usage

When using a bundler or Node.js you can import bson using the package name:

import { BSON, EJSON, ObjectId } from 'bson';
// or:
// const { BSON, EJSON, ObjectId } = require('bson');

const bytes = BSON.serialize({ _id: new ObjectId() });
console.log(bytes);
const doc = BSON.deserialize(bytes);
console.log(EJSON.stringify(doc));
// {"_id":{"$oid":"..."}}

Browser Usage

If you are working directly in the browser without a bundler please use the .mjs bundle like so:

<script type="module">
  import { BSON, EJSON, ObjectId } from './lib/bson.mjs';

  const bytes = BSON.serialize({ _id: new ObjectId() });
  console.log(bytes);
  const doc = BSON.deserialize(bytes);
  console.log(EJSON.stringify(doc));
  // {"_id":{"$oid":"..."}}
</script>

Installation

npm install bson

MongoDB Node.js Driver Version Compatibility

Only the following version combinations with the MongoDB Node.js Driver are considered stable.

| | bson@1.x | bson@4.x | bson@5.x | bson@6.x | | ------------- | ---------- | ---------- | ---------- | ---------- | | mongodb@6.x | N/A | N/A | N/A | ✓ | | mongodb@5.x | N/A | N/A | ✓ | N/A | | mongodb@4.x | N/A | ✓ | N/A | N/A | | mongodb@3.x | ✓ | N/A | N/A | N/A |

Documentation

BSON

API documentation

EJSON

EJSON.parse(text, [options])

| Param | Type | Default | Description | | ----------------- | -------------------- | ----------------- | ---------------------------------------------------------------------------------- | | text | string | | | | [options] | object | | Optional settings | | [options.relaxed] | boolean | true | Attempt to return native JS types where possible, rather than BSON types (if true) |

Parse an Extended JSON string, constructing the JavaScript value or object described by that string.

Example

const { EJSON } = require('bson');
const text = '{ "int32": { "$numberInt": "10" } }';

// prints { int32: { [String: '10'] _bsontype: 'Int32', value: '10' } }
console.log(EJSON.parse(text, { relaxed: false }));

// prints { int32: 10 }
console.log(EJSON.parse(text));

EJSON.stringify(value, [replacer], [space], [options])

| Param | Type | Default | Description | | ----------------- | ------------------------------------------- | ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | value | object | | The value to convert to extended JSON | | [replacer] | function | array | | A function that alters the behavior of the stringification process, or an array of String and Number objects that serve as a whitelist for selecting/filtering the properties of the value object to be included in the JSON string. If this value is null or not provided, all properties of the object are included in the resulting JSON string | | [space] | string | number | | A String or Number object that's used to insert white space into the output JSON string for readability purposes. | | [options] | object | | Optional settings | | [options.relaxed] | boolean | true | Enabled Extended JSON's relaxed mode | | [options.legacy] | boolean | true | Output in Extended JSON v1 |

Converts a BSON document to an Extended JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.

Example

const { EJSON } = require('bson');
const Int32 = require('mongodb').Int32;
const doc = { int32: new Int32(10) };

// prints '{"int32":{"$numberInt":"10"}}'
console.log(EJSON.stringify(doc, { relaxed: false }));

// prints '{"int32":10}'
console.log(EJSON.stringify(doc));

EJSON.serialize(bson, [options])

| Param | Type | Description | | --------- | ------------------- | ---------------------------------------------------- | | bson | object | The object to serialize | | [options] | object | Optional settings passed to the stringify function |

Serializes an object to an Extended JSON string, and reparse it as a JavaScript object.

EJSON.deserialize(ejson, [options])

| Param | Type | Description | | --------- | ------------------- | -------------------------------------------- | | ejson | object | The Extended JSON object to deserialize | | [options] | object | Optional settings passed to the parse method |

Deserializes an Extended JSON object into a plain JavaScript object with native/BSON types

Error Handling

It is our recommendation to use BSONError.isBSONError() checks on errors and to avoid relying on parsing error.message and error.name strings in your code. We guarantee BSONError.isBSONError() checks will pass according to semver guidelines, but errors may be sub-classed or their messages may change at any time, even patch releases, as we see fit to increase the helpfulness of the errors.

Any new errors we add to the driver will directly extend an existing error class and no existing error will be moved to a different parent class outside of a major release. This means BSONError.isBSONError() will always be able to accurately capture the errors that our BSON library throws.

Hypothetical example: A collection in our Db has an issue with UTF-8 data:

let documentCount = 0;
const cursor = collection.find({}, { utf8Validation: true });
try {
  for await (const doc of cursor) documentCount += 1;
} catch (error) {
  if (BSONError.isBSONError(error)) {
    console.log(`Found the troublemaker UTF-8!: ${documentCount} ${error.message}`);
    return documentCount;
  }
  throw error;
}

React Native

BSON vendors the required polyfills for TextEncoder, TextDecoder, atob, btoa imported from React Native and therefore doesn't expect users to polyfill these. One additional polyfill, crypto.getRandomValues is recommended and can be installed with the following command:

npm install --save react-native-get-random-values

The following snippet should be placed at the top of the entrypoint (by default this is the root index.js file) for React Native projects using the BSON library. These lines must be placed for any code that imports BSON.

// Required Polyfills For ReactNative
import 'react-native-get-random-values';

Finally, import the BSON library like so:

import { BSON, EJSON } from 'bson';

This will cause React Native to import the node_modules/bson/lib/bson.rn.cjs bundle (see the "react-native" setting we have in the "exports" section of our package.json.)

Technical Note about React Native module import

The "exports" definition in our package.json will result in BSON's CommonJS bundle being imported in a React Native project instead of the ES module bundle. Importing the CommonJS bundle is necessary because BSON's ES module bundle of BSON uses top-level await, which is not supported syntax in React Native's runtime hermes.

FAQ

Why does undefined get converted to null?

The undefined BSON type has been deprecated for many years, so this library has dropped support for it. Use the ignoreUndefined option (for example, from the driver ) to instead remove undefined keys.

How do I add custom serialization logic?

This library looks for toBSON() functions on every path, and calls the toBSON() function to get the value to serialize.

const BSON = require('bson');

class CustomSerialize {
  toBSON() {
    return 42;
  }
}

const obj = { answer: new CustomSerialize() };
// "{ answer: 42 }"
console.log(BSON.deserialize(BSON.serialize(obj)));