02 MongoDB Query
02 MongoDB Query
Introduction to MongoDB
DB
MG
MongoDB: Introduction
DB
MG
Terminology – Approximate mapping
DB
MG
MongoDB: Document Data Design
DB
MG
MongoDB: Document Data Design
DB
MG
MongoDB: Main features
DB
MG
6
MongoDB
DB
MG
MongoDB: query language
SELECT * db.people.find()
FROM people
DB
MG
MongoDB: Read data from documents
Select documents
db.<collection name>.find( {<conditions>},
{<fields of interest>} );
E.g.,
db.people.find();
Returns all documents contained in the people
collection
DB
MG
MongoDB: Read data from documents
Select documents
db.<collection name>.find( {<conditions>},
{<fields of interest>} );
Select the documents satisfying the specified
conditions and specifically only the fields
specified in fields of interest
<conditions> are optional
conditions take a document with the form:
{field1 : <value>, field2 : <value> ... }
Conditions may specify a value or a regular
expression
DB
MG
MongoDB: Read data from documents
Select documents
db.<collection name>.find( {<conditions>},
{<fields of interest>} );
Select the documents satisfying the specified
conditions and specifically only the fields
specified in fields of interest
<fields of interest> are optional
projections take a document with the form:
{field1 : <value>, field2 : <value> ... }
1/true to include the field, 0/false to exclude the
field
DB
MG
MongoDB: Read data from documents
E.g.,
db.people.find().pretty();
No conditions and no fields of interest
Returns all documents contained in the people
collection
pretty()displays the results in an easy-to-read
format
db.people.find({age:55})
One condition on the value of age
Returns all documents having age equal to 55
DB
MG
MongoDB: Read data from documents
DB
MG
MongoDB: find() operator
DB
MG
MongoDB: find() operator
Where Condition
SELECT id, db.people.find(
user_id, { },
status { user_id: 1,
FROM people status: 1
}
)
Select fields
DB
MG
MongoDB: find() operator
SELECT * db.people.find(
FROM people { status: "A" }
WHERE status = "A" )
Where Condition
DB
MG
MongoDB: find() operator
db.people.find(
{"address.city":“Rome" }
)
{ _id: "A",
address: { nested document
street: “Via Torino”,
number: “123/B”,
city: “Rome”,
code: “00184”
DB
}
MG }
MongoDB: Read data from documents
DB
MG
MongoDB: Read data from documents
DB
MG
MongoDB: (no) joins
DB
MG
MongoDB: (no) joins
(no) joins
Relations among documents/records are provided by
Object(ID) reference, with no native join
DBRef, across collections and databases
DB
MG https://docs.mongodb.com/manual/reference/database-references/
MongoDB: comparison operators
Name Description
$eq or : Matches values that are equal to a specified value
$gt Matches values that are greater than a specified value
$gte Matches values that are greater than or equal to a
specified value
$in Matches any of the values specified in an array
$lt Matches values that are less than a specified value
$lte Matches values that are less than or equal to a specified
value
$ne Matches all values that are not equal to a specified value
$nin Matches none of the values specified in an array
DB
MG
MongoDB: comparison operators (>)
SELECT * db.people.find(
FROM people { age: { $gt: 25 } }
WHERE age > 25 )
DB
MG
MongoDB: comparison operators (>=)
SELECT * db.people.find(
FROM people { age: { $gte: 25 } }
WHERE age >= 25 )
DB
MG
MongoDB: comparison operators (<)
SELECT * db.people.find(
FROM people { age: { $lt: 25 } }
WHERE age < 25 )
DB
MG
MongoDB: comparison operators (<=)
SELECT * db.people.find(
FROM people { age: { $lte: 25 } }
WHERE age <= 25 )
DB
MG
MongoDB: comparison operators (=)
SELECT * db.people.find(
FROM people { age: { $eq: 25 } }
WHERE age = 25 )
DB
MG
MongoDB: comparison operators (!=)
SELECT * db.people.find(
FROM people { age: { $neq: 25 } }
WHERE age != 25 )
DB
MG
MongoDB: conditional operators
DB
MG
MongoDB: conditional operators (AND)
SELECT * db.people.find(
FROM people { status: "A",
WHERE status = "A" age: 50 }
AND age = 50 )
DB
MG
MongoDB: conditional operators (OR)
SELECT * db.people.find(
FROM people { $or:
WHERE status = "A" [ { status: "A" } ,
OR age = 50 { age: 50 }
]
}
)
DB
MG
MongoDB: Cursor
Cursor examples:
db.people.find({ status: "A"}).count()
Select documents with status=“A” and count them.
DB
MG
MongoDB: sorting data
E.g.,
db.people.find({ status: "A"}).sort({age:1})
Select documents with status=“A” and sort them
in ascending order based on the age value
Returns all documents having status=“A”. The result
is sorted in ascending age order
DB
MG
MongoDB: sorting data
SELECT * db.people.find(
FROM people { status: "A" }
WHERE status = "A" ).sort( { user_id: 1 } )
ORDER BY user_id ASC
DB
MG
MongoDB: sorting data
SELECT * db.people.find(
FROM people { status: "A" }
WHERE status = "A" ).sort( { user_id: 1 } )
ORDER BY user_id ASC
SELECT * db.people.find(
FROM people { status: "A" }
WHERE status = "A" ).sort( { user_id: -1 } )
ORDER BY user_id DESC
DB
MG
MongoDB: counting
DB
MG
MongoDB: counting
DB
MG
MongoDB
DB
MG
Aggregation in MongoDB
DB
MG
MongoDB: Aggregation Framework
SQL MongoDB
WHERE $match
GROUP BY $group
HAVING $match
SELECT $project
ORDER BY $sort
//LIMIT $limit
SUM $sum
COUNT $sum
DB
MG
MongoDB: Aggregation
db.collection.aggregate({<set of stages>})
DB
MG
MongoDB: Aggregation
db.people.aggregate( [
{ $group: { _id: null,
mytotal: { $sum: "$age" },
mycount: { $sum: 1 }
}
}
] )
db.people.aggregate( [
{ $group: { _id: null,
myaverage: { $avg: "$age" },
mytotal: { $sum: "$age" }
}
}
] )
Considers all documents of people and computes
sum of age
average of age
DB
MG
MongoDB: Aggregation
DB
MG
MongoDB: Aggregation
db.people.aggregate( [
{ $group: { _id: "$status",
count: { $sum: 1 }
}
}
] )
Creates one group of documents for each value of
status and counts the number of documents per
group
Returns one value for each group containing the
value of the grouping field and an integer
representing the number of documents
DB
MG
MongoDB: Aggregation
db.people.aggregate( [
{ $group: { _id: "$status",
count: { $sum: 1 }
}
},
{ $match: { count: { $gte: 3 } } }
] )
Creates one group of documents for each value
of status and counts the number of documents
per group. Returns only the groups with at least
3 documents
DB
MG
MongoDB: Aggregation
db.people.aggregate( [
{ $group: { _id: "$status",
count: { $sum: 1 }
}
Having condition
},
{ $match: { count: { $gte: 3 } } }
] )
Creates one group of documents for each value
of status and counts the number of documents
per group. Returns only the groups with at least
3 documents
DB
MG
MongoDB: Aggregation Framework
SQL MongoDB
WHERE $match
GROUP BY $group
HAVING $match
SELECT $project
ORDER BY $sort
LIMIT $limit
SUM $sum
COUNT $sum
DB
MG
Aggregation in MongoDB: Group By
SELECT status,
AVG(age) AS total
FROM people
GROUP BY status
db.orders.aggregate( [
{
$group: {
_id: "$status",
total: { $avg: "$age" }
}
}
] )
DB
MG
Aggregation in MongoDB: Group By
SELECT status,
SUM(age) AS total
FROM people
GROUP BY status
db.orders.aggregate( [
{
$group: {
_id: "$status", Group field
total: { $sum: "$age" }
}
}
] )
DB
MG
Aggregation in MongoDB: Group By
SELECT status,
SUM(age) AS total
FROM people
GROUP BY status
db.orders.aggregate( [
{
$group: {
_id: "$status", Group field
total: { $sum: "$age" }
}
} Aggregation function
] )
DB
MG
Aggregation in MongoDB: Group By
MySQL clause MongoDB operator
HAVING aggregate($group, $match)
SELECT status,
SUM(age) AS total
FROM people
GROUP BY status
HAVING total > 1000
db.orders.aggregate( [
{
$group: {
_id: "$status",
total: { $sum: "$age" }
}
},
{ $match: { total: { $gt: 1000 } } }
] )
DB
MG
Aggregation in MongoDB: Group By
MySQL clause MongoDB operator
HAVING aggregate($group, $match)
SELECT status,
SUM(age) AS total
FROM people
GROUP BY status
HAVING total > 1000
db.orders.aggregate( [
{ Group stage: Specify
$group: { the aggregation field
_id: "$status", and the aggregation
total: { $sum: "$age" } function
}
},
{ $match: { total: { $gt: 1000 } } }
] )
DB
MG
Aggregation in MongoDB: Group By
MySQL clause MongoDB operator
HAVING aggregate($group, $match)
SELECT status,
SUM(age) AS total
FROM people
GROUP BY status
HAVING total > 1000
db.orders.aggregate( [
{ Group stage: Specify
$group: { the aggregation field
_id: "$status", and the aggregation
total: { $sum: "$age" } function
}
},
{ $match: { total: { $gt: 1000 Match
} } }Stage: specify
] ) the condition as in
DB
MG
HAVING
Aggregation in MongoDB
DB
MG
MongoDB Compass
DB
MG
MongoDB Compass
DB
MG
MongoDB Compass
DB
MG
Connect to local or remote instances of MongoDB.
MongoDB Compass
DB
MG
Get an overview of the data in list or table format.
MongoDB Compass
DB
MG Analyze query performance and get hints to speed it up.
MongoDB Compass
Build a pipeline
consisting of multiple
aggregation stages.
DB
MG
MongoDB Compass: Aggregation stages
DB
MG
MongoDB Compass: Aggregation stages
DB
MG
One group for each “vendor”.
MongoDB Compass: Pipelines
DB
MG
MongoDB
Indexing
DB
MG
MongoDB: Indexes
DB
MG
MongoDB: Indexes
DB
MG
MongoDB: Create new indexes
Creating an index
DB
MG
MongoDB: Indexes
DB
MG
MongoDB: Indexes
DB
MG
MongoDB: Indexes
Geospatial indexes
Two type of geospatial indexes are provided: 2d
and 2dsphere
A 2dsphere index supports queries that
calculate geometries on an earth-like sphere
Use a 2d index for data stored as points on a
two-dimensional plane.
E.g.,
db.places.createIndex( {location: “2dsphere”} )
$near syntax:
{
<location field>: {
$near: {
$geometry: {
type: "Point" ,
coordinates: [ <longitude> , <latitude> ]
},
$maxDistance: <distance in meters>,
$minDistance: <distance in meters>
}
}
}
DB
MG
MongoDB: Indexes
E.g.,
db.places.createIndex( {location: “2dsphere”} )
DB
MG
MongoDB: Indexes
E.g.,
db.places.find({location:
{$near:
{$geometry: {
type: "Point",
coordinates: [ -73.96, 40.78 ] },
$maxDistance: 5000}
}})
Find all the places within 5000 meters from the
specified GeoJSON point, sorted in order from
nearest to furthest
DB
MG
MongoDB: Indexes
Text indexes
Support efficient searching for string content in a
collection
Text indexes store only root words (no language-
specific stop words or stem)
E.g.,
db.reviews.createIndex( {comment: “text”} )
Wildcard ($**) allows MongoDB to index every
field that contains string data
E.g.,
db.reviews.createIndex( {“$**”: “text”} )
DB
MG