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:
- Insert a new listing with the fields:
name,neighbourhood_group_cleansed,room_type,accommodatesandprice - Insert three listings at once using
insertMany - Insert a listing providing your own
_id(for example, "mi-listado-1") - Create a new collection called
mis_favoritosby inserting a document with whatever fields you want - Verify that your documents were inserted correctly by finding them with
find()
Pro:
- Insert a listing with an additional field that does not exist in the others (for example,
destacado: true) - Try to insert two documents with the same
_id. What error do you get? - Insert 5 reviews into the
reviewscollection for one of your listings (remember to includelisting_id,dateandreviewer_id)
This work is under a Attribution-NonCommercial-NoDerivatives 4.0 International license.
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 bookWill you buy me a coffee?
This is how I keep writing without ads or paywalls.
Sure, it's on me!
Comments
There are no comments yet.