MongoDB

Database Structure

MongoDB stores data records as documents (specifically BSON documents) which are gathered together in collections. A database stores one or more collections of documents.

Basic Concepts

Databases

In one MongoDB Server, there can be multiple databases. Normally, for each application, we just need to connect and use one database only. But depending on your application structure, some applications (like microservices-structure applications) might require using multiple databases for different purposes. As a convention in Glife team, databases names should be all in Kebab-case format

Collections

One Database can store one or more collections. And a Collections can store one or more Documents. Collections are what RBDMs called Tables. Collections names should be camelCase but in plural form (eg. users, roles,...)

Documents

MongoDB stores data records as BSON documents. BSON is a binary representation of JSON documents, though it contains more data types than JSON. For the BSON spec, see bsonspec.org. See also BSON Types for more information.

MongoDB documents are composed of field-and-value pairs and have the following structure:

{
   field1: value1,
   field2: value2,
   field3: value3,
   ...
   fieldN: valueN
}

The value of a field can be any of the BSON data types, including other documents, arrays, and arrays of documents. For example, the following document contains values of varying types:

var mydoc = {
    _id: ObjectId("5099803df3f4948bd2f98391"),
    name: { first: "Alan", last: "Turing" },
    birth: new Date('Jun 23, 1912'),
    death: new Date('Jun 07, 1954'),
    contribs: [ "Turing machine", "Turing test", "Turingery" ],
    views : NumberLong(1250000)
}

The above fields have the following data types:

  • _id holds an ObjectId.
  • name holds an embedded document that contains the fields first and last.
  • birth and death hold values of the Date type.
  • contribs holds an array of strings.
  • views holds a value of the NumberLong type.

Notes

Documents have some special attributes that you should keep in mind

  • Size Limit: The maximum BSON document size is 16 megabytes.
  • Field Order: Unlike JSON, the fields in a BSON document are ordered. So {a: 1, b: 1} is not equal to {b: 1, a: 1}
  • The _id Field: each document stored in a collection requires a unique _id field that acts as a primary key. If an inserted document omits the _id field, the MongoDB driver automatically generates an ObjectId for the _id field.

Connection URI

To connect to a MongoDB database you will need a Connection URI to provide to the drivers.

The connection URI is the set of instructions that the driver uses to connect to a MongoDB deployment. It instructs the driver on how it should connect to MongoDB and how it should behave while connected. The following example shows each part of the connection URI:

MongoDB Connection URI

  • protocol: A required prefix to identify that this is a string in the standard connection format. Besides mongodb there's also a protocol with +srv, you can check this document for more information.
  • user:pass: Optional. Authentication credentials. If specified, the client will attempt to authenticate the user to the authSource. If authSource is unspecified, the client will attempt to authenticate the user to the defaultauthdb. And if the defaultauthdb is unspecified, to the admin database. See MongoDB Security Docs to learn more about how to set up MongoDB Authentication.

Note

If the username or password includes the following characters : / ? # [ ] @, those characters must be converted using percent encoding (like URI Encoding)

  • sample.host[:port]: The host where the MongoDB server is running. It can be a hostname, IP address, or UNIX domain socket. If the port number is not specified, the default MongoDB port 27017 is used.
  • ?<options>: Optional. A query string that specifies connection-specific options as <name>=<value> pairs. See Connection String Options for a full description of these options

Basic driver usage

Below is a NodeJS example of how to connect to MongoDB using connection URI and get the first user from users collection in glife-website database

const { MongoClient } = require("mongodb");

// Connection URI
const uri =
  "mongodb://sample-hostname:27017/?maxPoolSize=20&w=majority"

// Create a new MongoClient
const client = new MongoClient(uri)

async function run() {
  try {
    // Connect the client to the server
    await client.connect()

    // Once connected you can use the client to get the references to database and collection
    const database = client.db("glife-website")
    const userCollection = database.collection("users")

    const user = await userCollection.findOne()

    // this method will return the first document in "users" collection
    console.log(user)
  } finally {
    // Ensures that the client will close when you finish/error
    await client.close();
  }
}

run().catch(console.dir);
Previous
Introduction