MongoDB

MongoDB is a widely-used NoSQL database recognized for its flexibility, scalability, and performance.

Unlike traditional relational databases that require a predefined schema, MongoDB allows for a dynamic schema. This means you can store documents with varying structures within the same collection, elimate the need for schema management, like schema migrations.

Additionally, MongoDB employs its own query language, which is based on JavaScript, making it accessible for novice web developers without requiring them to learn SQL.

These features have significantly contributed to MongoDB's success.

Setup

docker run --name my-mongodb -p 27017:27017 -d mongo

Talk to MongoDB

Using mongosh:

docker exec -it my-mongodb mongosh
test> use mydb
switched to db mydb
mydb> db.mycoll.insertOne({name: 'Alice'})
{
  acknowledged: true,
  insertedId: ObjectId('66f8b8ee56e5da57011681ed')
}
mydb> db.mycoll.findOne({name: 'Alice'})
{ _id: ObjectId('66f8b8ee56e5da57011681ed'), name: 'Alice' }

Using the JavaScript client:

npm i --save mongodb
const { MongoClient } = require('mongodb')

async function main() {
  const client = new MongoClient('mongodb://localhost:27017')
  await client.connect()
  const db = client.db('mydb')
  const mycoll = db.collection('mycoll')
  console.log(await mycoll.find().toArray())
}

main()