The EJSON.serialize() method converts BSON objects to Extended JSON
representation as JavaScript objects.
MongoDB stores data using BSON. Many external data transformation
applications use JSON. You can use EJSON.serialize() to convert BSON
to JSON and save the output for those external applications.
Syntax
The method has this syntax:
EJSON.serialize( object, [ options ] )
Method Fields
The method takes the following fields:
Field | Type | Necessity | Description | ||||||
|---|---|---|---|---|---|---|---|---|---|
| BSON object | Required | BSON object to convert. For example, an array of documents. | ||||||
| string | Optional | Modifies the output object types.
The only option is
|
Behavior
You can run EJSON.serialize() from an interactive mongosh
session or from the system command line using --eval.
To run EJSON.serialize() from an interactive mongosh session,
use:
EJSON.serialize( object, [ options ] )
To run EJSON.serialize() from the system command line, use:
mongosh --eval "EJSON.serialize( object, [ options ] )"
Examples
Create the sales collection for the examples:
db.sales.insertMany( [ { custId: 345, purchaseDate: ISODate("2023-07-04"), quantity: 4, cost: Decimal128("100.60") }, { custId: 346, purchaseDate: ISODate("2023-07-12"), quantity: 3, cost: Decimal128("175.45") }, { custId: 486, purchaseDate: ISODate("2023-08-01"), quantity: 9, cost: Decimal128("200.53") } ] )
Interactive Mongo Shell EJSON.serialize() Example
The following example retrieves the sales documents as an array and
stores the results in the salesCollection object:
salesCollection = EJSON.serialize( db.sales.find().toArray() )
Example output, which uses JSON:
[ { _id: { '$oid': '6520519a0dbd2d208a5c7941' }, custId: 345, purchaseDate: { '$date': '2023-07-04T00:00:00Z' }, quantity: 4, cost: { '$numberDecimal': '100.60' } }, { _id: { '$oid': '6520519a0dbd2d208a5c7942' }, custId: 346, purchaseDate: { '$date': '2023-07-12T00:00:00Z' }, quantity: 3, cost: { '$numberDecimal': '175.45' } }, { _id: { '$oid': '6520519a0dbd2d208a5c7943' }, custId: 486, purchaseDate: { '$date': '2023-08-01T00:00:00Z' }, quantity: 9, cost: { '$numberDecimal': '200.53' } } ]
Command Line Mongo Shell EJSON.serialize() Example
To save collection data to a file, you can use EJSON.serialize()
with the mongosh --eval method.
The following example retrieves the sales documents as an array and
saves the results to a file named sales.json on the computer's file
system:
# Note: The example is formatted to fit the page. mongosh --quiet \ --eval "EJSON.serialize( db.sales.find().toArray() )" \ > sales.json
You could then use the sales.json file with an external data
transformation application.
Learn More
EJSON documentation