TExcelTAD
Home › MongoDB › MongoDB Get Started

MongoDB Get Started

To work with MongoDB you need two things: a server that stores the data, and a client to talk to it. The most common client for learning and administration is mongosh, the MongoDB Shell.

Option 1: MongoDB Atlas (cloud)

Atlas is MongoDB's hosted service and has a free tier, so nothing has to be installed except the shell:

  1. Create an account on the Atlas website and create a free cluster.
  2. Add a database user (username + password) and allow your IP address under Network Access.
  3. Click Connect → Shell to copy a connection string that looks like mongodb+srv://cluster0.abcde.mongodb.net/.

Option 2: run it locally

MongoDB Community Server runs on Linux, macOS and Windows. The quickest way to get one is Docker:

bash
docker run -d --name mongo -p 27017:27017 mongo:8.0

Or use your system's package manager (for example brew install mongodb-community on macOS, after adding MongoDB's tap). The server listens on port 27017 by default.

Install and start mongosh

Download mongosh from MongoDB's site or install it with a package manager (brew install mongosh, npm install -g mongosh). Then connect:

bash
mongosh                                         # local server, database "test"
mongosh "mongodb://localhost:27017/shop"        # local server, database "shop"
mongosh "mongodb+srv://cluster0.abcde.mongodb.net/shop" --username ada

You get an interactive prompt. Type a command, press Enter, and mongosh prints the result:

text
test> db.getName()
test
test> 1 + 2
3

mongosh is a full JavaScript (Node.js) environment, so variables, functions, loops and const all work.

Interactive shell vs scripts

In the interactive shell, the value of each expression is printed automatically. Scripts are different. When you run a file with mongosh --file script.js (or load('script.js') inside the shell), nothing is printed unless you ask for it. All examples on this site are scripts, so they print explicitly:

Function Prints
print(value, ...) values in the same style as the interactive shell (short documents on one line)
printjson(value) one value, always expanded with one field per line
console.log(...) the same as print
mongosh · try it yourself
const answer = 6 * 7;
print('The answer is', answer);
print({ product: 'Espresso Beans', price: 24.5 });
printjson({ product: 'Espresso Beans', price: 24.5 });
The answer is 42
{ product: 'Espresso Beans', price: 24.5 }
{
  product: 'Espresso Beans',
  price: 24.5
}

The db variable

db is the current database. db.getName() tells you which one it is, and db.<collection> gives you a collection object with methods like find, insertOne and updateMany:

mongosh · try it yourself
print(typeof db.getName());
print(db.products.findOne({ _id: 7 }));
string
{
  _id: 7,
  name: 'Earl Grey',
  category: 'tea',
  price: 9.5,
  stock: 80,
  tags: [ 'black', 'bags' ],
  rating: 4.1
}

The name of the database differs on every run of the verifier, which is why the first line prints only its type.

Cursors need .toArray()

find() doesn't return documents directly. It returns a cursor, an object that fetches results from the server in batches. In the interactive shell a cursor prints its first 20 documents automatically, but in a script you should turn it into an array (or loop over it) before printing:

mongosh · try it yourself
const cheap = db.products.find({ price: { $lt: 5 } }, { name: 1, price: 1 });
print(cheap.toArray());
[
  { _id: 17, name: 'Dark Chocolate Bar', price: 4.5 },
  { _id: 19, name: 'Salted Pretzels', price: 3.5 }
]

Tip: Another way is to loop: db.products.find().forEach(p => print(p.name)). You will see both styles throughout the course.

Common mistakes

  • Forgetting the quotes on strings. { name: Earl Grey } is a syntax error; write { name: 'Earl Grey' }.
  • Expecting output from a script. If your script runs but shows nothing, you forgot print/printjson.
  • Printing a cursor in old code. Code written for the legacy mongo shell sometimes relies on cursors printing themselves. In scripts, use .toArray().

Test yourself

What is the default port of a MongoDB server?

  1. 3306
  2. 5432
  3. 27017
  4. 8080

Your script report.js runs db.products.countDocuments() but prints nothing. Why?

  1. countDocuments() needs .toArray()
  2. Scripts don't auto-print results; wrap the call in print()
  3. The collection is empty
  4. mongosh can't run files

What does db.products.find() return?

  1. An array of documents
  2. A single document
  3. A cursor
  4. The number of matches