3. Basic concepts

Let's work with the fundamental concepts of MongoDB.

Databases and collections

In MongoDB, a database contains multiple collections, and each collection contains multiple documents.

To create or switch to a database:

use learn

It doesn't matter that the database doesn't exist yet. It will be created automatically when you insert the first document.

To see all the databases:

show dbs

To see the collections in the current database:

show collections

To see information about the current database:

db.stats()

Documents

Documents are JSON objects (technically BSON) that store your data. Each document must have a unique _id field.

Example document:

{
    _id: ObjectId("507f1f77bcf86cd799439011"),
    name: "Aurora",
    age: 25,
    email: "aurora@example.com",
    hobbies: ["reading", "programming"],
    address: {
        city: "Madrid",
        country: "Spain"
    }
}

Notice that:

  • Fields can be of different types (strings, numbers, arrays, objects)
  • You can have arrays directly
  • You can have embedded documents (objects within objects)
  • The _id is generated automatically if you don't provide it

The _id field

Each document must have a unique _id field. If you don't provide it, MongoDB automatically generates an ObjectId.

An ObjectId is a 12-byte identifier that guarantees uniqueness:

ObjectId("507f1f77bcf86cd799439011")

You can provide your own _id:

db.users.insertOne({
    _id: 1,
    name: "María"
})

But you will usually let MongoDB generate it automatically.

Basic queries

To work with the data you need to know these fundamental commands:

countDocuments: counts the number of documents in a collection

// Count all documents
db.listings.countDocuments()

// Count with a filter (we'll see this later)
db.listings.countDocuments({ room_type: "Entire home/apt" })

stats: gets detailed statistics for a collection

db.listings.stats()

You will see information such as:

  • Number of documents (count)
  • Total size of the data (size)
  • Average size of each document (avgObjSize)
  • Number of indexes
Activity 1

Now that you have imported the Airbnb data, let's explore its basic structure:

  1. Count how many listings there are in the listings collection
  2. Count how many reviews there are in the reviews collection
  3. Use stats() to see the statistics of the listings collection

Pro:

  1. Compare the number of documents in listings vs reviews. Which one has more documents?
  2. Using stats(), calculate how many reviews there are on average per listing (divide the total reviews by the total listings)
  3. Which collection takes up more disk space? Use the size field from stats() to compare

Solutions

This work is under a Attribution-NonCommercial-NoDerivatives 4.0 International license.

Desafíos de programación atemporales y multiparadigmáticos

Desafíos de programación atemporales y multiparadigmáticos

Te encuentras ante un librillo de actividades, divididas en 2 niveles de dificultad. Te enfrentarás a los casos más comunes que te puedes encontrar en pruebas técnicas o aprender conceptos elementales de programación.

Buy the book

Will you buy me a coffee?

This is how I keep writing without ads or paywalls.

Comments

There are no comments yet.