4. Querying documents
Now that you have imported Airbnb data, you will learn to read and explore it.
The find command
To get all the documents in a collection:
db.listings.find()
This returns the first 20 documents. To see more, type it (iterate).
Searching for specific documents
You can use a filter to search for documents that meet certain conditions:
// Listings in the CIUTAT VELLA neighborhood
db.listings.find({ neighbourhood_group_cleansed: "CIUTAT VELLA" })
// Listings of type "Entire home/apt"
db.listings.find({ room_type: "Entire home/apt" })
The filter is an object with field-value pairs. MongoDB returns only the documents where those fields have those exact values.
The findOne command
To get just one document (useful for seeing the structure):
// Gets the first listing
db.listings.findOne()
// Gets a specific listing
db.listings.findOne({ room_type: "Private room" })
findOne returns a single document instead of a cursor.
Projections
You can select which fields to return using projections:
// Only returns name and price (and _id by default)
db.listings.find(
{ neighbourhood_group_cleansed: "EXTRAMURS" },
{ name: 1, price: 1 }
)
// Excludes the _id field
db.listings.find(
{ neighbourhood_group_cleansed: "EXTRAMURS" },
{ name: 1, price: 1, _id: 0 }
)
In projections: - 1 means "include this field" - 0 means "exclude this field"
You cannot mix inclusions and exclusions (except with _id).
Counting documents
You already know countDocuments from the previous lesson. Now you can use it with filters:
// Count listings in a specific neighborhood
db.listings.countDocuments({ neighbourhood_group_cleansed: "BENIMACLET" })
// Count superhosts
db.listings.countDocuments({ host_is_superhost: "t" })
Activity 1
Practice basic queries with the Airbnb listings:
- Find all listings in the CIUTAT VELLA neighborhood
- Find listings of type "Entire home/apt" (
room_type) - Find a single listing that is a "Private room"
- Show only the
name,priceandhost_namefields of listings in POBLATS MARITIMS - Count how many listings there are in the BENIMACLET neighborhood
Pro:
- Find listings where the host is a superhost (
host_is_superhostis"t") - Find a listing in the RASCANYA neighborhood and show only its name and room type
- Count how many "Private room" listings there are in the EXTRAMURS neighborhood (combine filters in a single object)
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.