What is BSON and exactly how is it different from JSON? - json

I am just starting out with MongoDB and one of the things that I have noticed is that it uses BSON to store data internally. However the documentation is not exactly clear on what BSON is and how it is used in MongoDB. Can someone explain it to me, please?

BSON is the binary encoding of JSON-like documents that MongoDB uses when storing documents in collections. It adds support for data types like Date and binary that aren't supported in JSON.
In practice, you don't have to know much about BSON when working with MongoDB, you just need to use the native types of your language and the supplied types (e.g. ObjectId) of its driver when constructing documents and they will be mapped into the appropriate BSON type by the driver.

What's BSON?
BSON [bee · sahn], short for Bin­ary JSON, is a bin­ary-en­coded
seri­al­iz­a­tion of JSON-like doc­u­ments.
How is it different from JSON?
BSON is designed to be efficient in space, but in some cases is not much more efficient than JSON. In some cases BSON uses even more space than JSON. The reason for this is another of the BSON design goals: traversability. BSON adds some "extra" information to documents, like length of strings and subobjects. This makes traversal faster.
BSON is also designed to be fast to encode and decode. For example, integers are stored as 32 (or 64) bit integers, so they don't need to be parsed to and from text. This uses more space than JSON for small integers, but is much faster to parse.
In addition to compactness, BSON adds additional data types unavailable in JSON, notably the BinData and Date data types.
Source: http://bsonspec.org/

MongoDB represents JSON documents in binary-encoded format so we call it BSON behind the scenes.
BSON extends the JSON model to provide additional data types such  as Date and binary which are not supported in JSON also provide ordered fields in order for it to be efficient for encoding and decoding within different languages. 
In other word we can say  BSON is just binary JSON ( a superset of JSON with some more data types, most importantly binary byte array ).
Mongodb using as a serialization format of JSON include with encoding format for storing and accessing documents. simply we can say BSON is a binary encoded format for JSON data.
for more mongoDB Article : https://om9x.com/blog/bson-vs-json/

MongoDB represents JSON documents in binary-encoded format called BSON behind the scenes. BSON extends the JSON model to provide additional data types and to be efficient for encoding and decoding within different languages.

By using BSON encoding on top of JSON, MongoDB gets the capability of creating indexes on top of values that resides inside the JSON document in raw format. This helps in running efficient analytical queries as NoSQL system were known for having no support for Indexes.

This relatively short article gives a pretty good explanation of BSON and JSON: It talks about some of the problems with JSON, why BSON was invented, what problems it solves compared to JSON and how it could benefit you.
https://www.compose.com/articles/from-json-to-bson-and-back/
In my use case that article told me that serializing to JSON would work for me and I didn't need to serialize to BSON

To stay strictly within the boundaries of the OP question:
What is BSON?
BSON is a specification for a rich set of scalar types (int32, int64, decimal, date, etc.) plus containers (object a.k.a. a map, and array) as they might appear in a byte stream. There is no "native" string form of BSON; it is a byte[] spec. To work with this byte stream, there are many native language implementations available that can turn the byte stream into actual types appropriate for the language. These are called codecs. For example, the Java implementation of a BSON codec into the Document class from MongoDB turns objects into something that implements java.util.Map. Dates are decoded into java.util.Date. Transmitting BSON looks like this in, for example, Java and python:
Java:
import org.bson.*;
MyObject --> get() from MyObject, set() into org.bson.Document --> org.bson.standardCodec.encode(Document) to byte[]
XMIT byte[]
python:
import bson
byte[] --> bson.decode(byte[]) to dict --> get from dict --> do something
There are no to- and from- string calls involved. There is no parser. There is nothing about whitespace and double quotes and escaped characters. Dates, BigDecimal, and arrays of Long captured on the Java side reappear in python as datetime.datetime, Decimal, and array of int.
In comparison, JSON is a string. There is no codec for JSON. Transmitting JSON looks like this:
MyObject --> convert to JSON (now you have a big string with quotes and braces and commas)
XMIT string
parse string to dict (or possibly a class via a framework)
Superficially this looks the same but the JSON specification for scalars has only strings and "number" (leaving out bools and nulls, etc.). There is no direct way to send a long or a BigDecimal from sender to receiver in JSON; they are both just "number". Furthermore, JSON has no type for plain byte array. All non-ASCII data must be base64 or otherwise encoded in a way to protect it and sent as a string. BSON has a byte array type. The producer sets it, the consumer gets it. There is no secondary processing of strings to turn it back into the desired type.
How does MongoDB use BSON?
To start, it is the wire protocol for content. It also is the on-disk format of data. Because varying length types (most notably string) carry length information in the BSON spec, this permits MongoDB to performantly traverse an object (hopping field to field). Finding the object in a collection is more than just BSON including use of indexes.

Related

Question about JSON vs CBOR serialization

I have a theorical doubt about how serialization works, and especially about the difference between serialization schemes like JSON and binary serialization schemes like CBOR.
My question is: if a JSON serializer converts an object into a JSON string, then, to store or transmit the resulting JSON string, do you have to also convert the JSON string into its bytes representation? Is this why binary schemes might be faster, since they produce a binary output already?
In memory, a string is anyway represented as a sequence of bytes (actually, everything is just a sequence of bytes in memory), so this should not matter.
What matters is the conversion from the in-memory representation of a Javascript variable into its in-memory representation of its string equivalent. An extremely simply example is a numeric variable with value -1. This can be internally represented by one byte:
> Buffer.of(-1)
<Buffer ff>
but its JSON serialization "-1" takes two bytes:
> Buffer.from(JSON.stringify(-1))
<Buffer 2d 31>
This should give an idea why a binary scheme that sticks closer to the internal representation can be output (and input) faster.

Prevent parsing a JSON node with common-lisp YASON library

I am using the Yason library in common-lisp, I want to parse a json string but would like the parser to keep one a its node unparsed.
Typically with an example like that:
{
"metadata1" : "mydata1",
"metadata2" : "mydata2",
"payload" : {...my long payload object},
"otherNodesToParse" : {...}
}
How can I set the yason parser to parse my json but skip the payload node and keep it as a string in the json format.
Use: let's say I just want the envelope data (everything that's not the payload), and to forward the payload as-is (as json string) to another system.
If I parse the whole json (so including payload) and then re-encode the payload to json, it is inefficient. The payload size could also be pretty big.
How do you know where the end of the payload object is in the stream? You do so by parsing the stream: if you don't parse the stream you simply can't know where the end of the object is: that's the nature of JSON's syntax (as it is the nature of CL's default syntax). For instance the only way you can know the difference between where to continue after
{x:1}
and after
{x:1.2}
is by parsing the two things.
So you must necessarily parse the whole thing.
So the answer to your question is: you can't do this.
You could (but not, I think, with YASON) decide that you did not want to build an object as a result of the parse. And perhaps, if the stream you are parsing corresponds to something with random access like a string or a file, you could note the start and end positions in the stream to later extract a string from it corresponding to the unparsed data (or you could perhaps build it up as you go).
It looks as if some or all of this might be possible with CL-JSON, but you'd have to work at it.
Unless the objects you are reading are vast the benefit of this seems questionable-to-none. If you really do want to do something like this efficiently you need a serialisation scheme which tells you how long things are.

Library to convert JSON string to Erlang record

I've a large JSON string, I want to convert this string into Erlang record.
I found jiffy library but it doesn't completely convert to record.
For example:
jiffy:decode(<<"{\"foo\":\"bar\"}">>).
gives
{[{<<"foo">>,<<"bar">>}]}
but I want the following output:
{ok,{obj,[{"foo",<<"bar">>}]},[]}
Is there any library that can be used for the desired output?
Or is there any library that can be used in combination of jiffy for further modifying the output of it.
Consider the fact the JSON string is large, and I want the output is minimum time.
Take a look at ejson, from the documentation:
JSON library for Erlang on top of jsx. It gives a declarative interface for jsx by which we need to specify conversion rules and ejson will convert tuples according to the rules.
I made this library to make easy not just the encoding but rather the decoding of JSONs to Erlang records...
In order for ejson to take effect the source files need to be compiled with parse_transform ejson_trans. All record which has -json attribute can be converted to JSON later.

JSON definition - data structure or data format?

What is more correct? Say that JSON is a data structure or a data format?
It's almost certainly ambiguous and depends on your interpration of the words.
The way I see it:
A datastructure, in conventional Comp Sci / Programming i.e. array, queue, binary tree usually has a specific purpose. Json can be pretty much be used for anything, hence why it's a data-format. But both definitions make sense
In my opinion both is correct.
JSON is also a data format (.json) and also a data strucuture which you can use for instance in Java etc.
But more correct is data strucutre.
JSON (canonically pronounced /ˈdʒeɪsən/ jay-sən;[1] sometimes
JavaScript Object Notation) is an open-standard format that uses
human-readable text to transmit data objects consisting of
attribute–value pairs. It is the most common data format used for
asynchronous browser/server communication (AJAJ), largely replacing
XML which is used by AJAX.
Source: Wikipedia

How to convert between BSON and JSON, especially for those special objects?

I am not asking for any libraries to do so and I am just writing code for bson_to_json and json_to_bson.
so here is the BSON specification.
For regular double, doc, array, string, it is fine and it is easy to convert between BSON and JSON.
However, for those particular objects, such as
Timestamp and UTC:
If convert from JSON to BSON, how can I know they are timestamp and utc?
Regex (string, string), JavaScript code with scope (string, doc)
their structures have multiple parts, how can I present the structures in JSON?
Binary data (generic, function, etc)`
How can I present the type of binary data in JSON?
int32 and int64
How can I present them in JSON, so BSON can know which is 32 bit or 64 bit?
Thanks
As we know JSON cannot express objects so you will need to decide how you want the stringified version of the BSON objects (field types) to be represented within the output of your ocaml driver.
Some of the data types are easy, Timestamp is not needed since it is internal to sharding only and Javascript blocks are best left out due to the fact that they are best used only within system.js as saved functions for use in MRs.
You also gotta consider that some of these fields are actually both in and out. What I mean by in and out is that some are used to specify input documents to be serialised to BSON and some are part of output document that need deserialising from BSON into JSON.
Regex is one which will most likely be a field type you send down. As such you will need to serialise your ocaml object to the BSON equivilant of {$regex: 'd', '$options': 'ig'} from /d/ig PCRE representation.
Dates can be represented in JSON by either choosing to use the ISODate string or a timestamp for the representation. The output will be something like {$sec:556675,$usec:6787} and you can convert $sec to the display you need.
Binary data in JSON can be represented by taking the data (if I remember right) property from the output document and then encoding that to base 64 and storing it as a stirng in the field.
int32 and int64 has no real definition between the two in JSON except that 64bit ints will be bigger than 2147483647 so I am unsure if you can keep the data types unique there.
That should help get you started.