Grokking MongoDB
Vote

0% completed

​

Introduction to JSON

The JSON Syntax

JSON and the mongosh Syntax

Field Order

How MongoDB Uses JSON

What JSON Cannot Express

Here is the same user written in two ways. The first is a line of comma-separated values, and the second is JSON.

John Doe,30,john.doe@example.com,false
{ "name": "John Doe", "age": 30, "email": "john.doe@example.com", "isStudent": false }

To read the first line, you must already know what each position means. The second form includes that knowledge in the data, because every value has a name beside it. It also shows that 30 is a number and false is a Boolean, whereas every value in the first line is only text.

JSON stands for JavaScript Object Notation. It is a text format for structured data that people can read and that programs can easily parse and generate. It began with the object syntax of JavaScript, but it is independent of any language, and parsers exist for almost every programming language.

The JSON Syntax

The block above is a JSON object: a list of key and value pairs inside curly braces. Keys are always strings. A value can be one of six types:

  • A string in double quotes, such as "John Doe".
  • A number, such as 30 or 19.99.
  • A Boolean, which is true or false.
  • null.
  • An object.
  • An array, which is an ordered list in square brackets.

The last two allow JSON to describe nested data. Here the user's address is an object inside the main object:

{ "firstName": "Jane", "lastName": "Doe", "age": 25, "address": { "street": "123 Main St", "city": "Anytown", "zipcode": "12345" } }

MongoDB documents have the same structure, which is why this nesting fits MongoDB well. Jane's address can stay inside her record, and it does not need a separate collection.

JSON and the mongosh Syntax

JSON has strict rules. Keys need double quotes, and a comma after the last item is not allowed. A strict parser rejects text that breaks either rule:

JSON.parse("{ name: 'John Doe' }") JSON.parse('{ "age": 30, }')
Expected property name or '}' in JSON at position 2 Expected double-quoted property name in JSON at position 13

The commands you type in mongosh look similar to JSON, but they are JavaScript, and JavaScript is more relaxed. For that reason, { name: "John Doe" } is accepted in a mongosh command even though it is not valid JSON. The output of mongosh also uses this relaxed form, with name: 'John Doe' in place of "name": "John Doe". If you copy a document into a program that expects real JSON, you must convert it first.

Field Order

The JSON standard describes an object as an unordered set of pairs, so a JSON parser may treat two objects with the same pairs as equal. MongoDB does not. It keeps the fields in the order you wrote them, with two exceptions: _id always moves to the first position, and renaming a field can change its position. That order can change the result of a query. In the commands below, countDocuments() reports how many documents match a condition.

db.users.drop() db.users.insertOne({ name: "John Doe", address: { street: "123 Main St", city: "Anytown" } }) db.users.countDocuments({ address: { street: "123 Main St", city: "Anytown" } }) db.users.countDocuments({ address: { city: "Anytown", street: "123 Main St" } }) db.users.countDocuments({ "address.city": "Anytown" })
1 0 1

The second filter finds nothing, because comparing a whole nested document also compares the order of its fields. The third filter checks one field by its path, and the order does not affect it.

How MongoDB Uses JSON

You write queries and documents in a form close to JSON, and results come back in that form, which makes data easy to read. This does not mean that MongoDB stores JSON text. The server stores and transfers documents in a binary format based on the JSON structure.

JSON is also common outside MongoDB, in web APIs that exchange data between a server and a client, in configuration files, and in data exchange between different systems. Because it is compact for a text format, it suits transfer over a network. This wide use is an advantage for MongoDB, because a JSON request received by a web application is already close to the shape of a document.

What JSON Cannot Express

JSON has only the six types listed above, and that limit matters as soon as you store real data. It has no date type, and converting a JavaScript date to JSON produces a plain string:

JSON.stringify({ name: "John Doe", createdAt: new Date("2023-06-01T00:00:00Z") })
{"name":"John Doe","createdAt":"2023-06-01T00:00:00.000Z"}

A program reading this text sees a string, and nothing tells it that the value is a date. JSON also has a single number type, with no separate integer or exact decimal, and it has no way to represent raw bytes.

Reading Progress

0%


Vote for new content

On This Page

The JSON Syntax

JSON and the mongosh Syntax

Field Order

How MongoDB Uses JSON

What JSON Cannot Express