6. Inserting documents

So far you have only queried the imported data. It's time to learn how to create your own documents.

Inserting a document

To insert a single document use insertOne:

db.listings.insertOne({
    name: "My apartment in Barcelona",
    neighbourhood_group_cleansed: "EIXAMPLE",
    room_type: "Entire home/apt",
    accommodates: 4,
    price: "$75.00"
})

MongoDB returns an object with the automatically generated _id:

{
    acknowledged: true,
    insertedId: ObjectId("507f1f77bcf86cd799439011")
}

Inserting multiple documents

To insert several documents at once use insertMany:

db.listings.insertMany([
    {
        name: "Private room in Gràcia",
        neighbourhood_group_cleansed: "EXTRAMURS",
        room_type: "Private room",
        accommodates: 2,
        price: "$40.00"
    },
    {
        name: "Studio in Ciutat Vella",
        neighbourhood_group_cleansed: "CIUTAT VELLA",
        room_type: "Entire home/apt",
        accommodates: 2,
        price: "$65.00"
    }
])

MongoDB returns the IDs of all the inserted documents.

Automatic collections

If the collection does not exist, it will be created automatically when you insert the first document:

// This collection does not exist yet
db.mis_propiedades.insertOne({ name: "My first property" })
// Now it exists

The _id field

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

// MongoDB generates the _id automatically
db.listings.insertOne({ name: "Beach house" })

// You can provide your own _id
db.listings.insertOne({
    _id: "mi-id-personalizado",
    name: "Downtown apartment"
})

Important: The _id must be unique. If you try to insert a document with an _id that already exists, the operation will fail.

Data validation

MongoDB does not automatically validate your data. You can insert documents with different structures in the same collection:

// All valid in the same collection
db.pruebas.insertMany([
    { name: "Ana", age: 28 },
    { name: "Carlos", city: "Madrid" },  // No age field
    { email: "laura@example.com" }        // No name or age fields
])

This is flexible, but you must be careful with the consistency of your data.

Activity 1

Practice inserting new listings into the Airbnb database:

  1. Insert a new listing with the fields: name, neighbourhood_group_cleansed, room_type, accommodates and price
  2. Insert three listings at once using insertMany
  3. Insert a listing providing your own _id (for example, "mi-listado-1")
  4. Create a new collection called mis_favoritos by inserting a document with whatever fields you want
  5. Verify that your documents were inserted correctly by finding them with find()

Pro:

  1. Insert a listing with an additional field that does not exist in the others (for example, destacado: true)
  2. Try to insert two documents with the same _id. What error do you get?
  3. Insert 5 reviews into the reviews collection for one of your listings (remember to include listing_id, date and reviewer_id)

Solutions

Building SPAs with Django and HTML Over the Wire: Learn to build real-time single page applications with Python

Building SPAs with Django and HTML Over the Wire: Learn to build real-time single page applications with Python

The HTML over WebSockets approach simplifies single-page application (SPA) development and lets you bypass learning a JavaScript rendering framework such as React, Vue, or Angular, moving the logic to Python. This web application development book provides you with all the Django tools you need to simplify your developments with real-time results.

Buy the book

Help me keep writing

Every coffee gives me a push toward the next article.

Comments

There are no comments yet.