03 - Mongodb - Queries
03 - Mongodb - Queries
3
MongoDB CRUD Operations
4
MongoDB CRUD Operations
5
MongoDB CRUD Operations
6
MongoDB CRUD Operations
7
MongoDB CRUD Operations
MongoDB Queries
Read operations, or queries, retrieve data stored in the database. In MongoDB,
queries select documents from a single collection.
Queries specify criteria, or conditions, that identify the documents that MongoDB
returns to the clients. A query may include a projection that specifies the fields from
the matching documents to return. The projection limits the amount of data that
MongoDB returns to the client over the network.
The following diagram highlights the components of a MongoDB query operation:
8
MongoDB CRUD Operations
MongoDB Queries
Query Interface
For query operations, MongoDB provides a db.collection.find() method. The method
accepts both the query criteria and projections and returns a cursor to the matching
documents. You can optionally modify the query to impose limits, skips, and sort
orders.
The following diagram highlights the components of a MongoDB query operation:
9
MongoDB CRUD Operations
MongoDB Queries
Query Interface
The next diagram shows the same query in SQL:
10
MongoDB CRUD Operations
MongoDB Queries
Query Interface
This query selects the documents in the users collection that match the
condition age is greater than 18. To specify the greater than condition, query criteria
uses the greater than (i.e. $gt) query selection operator.
The query returns at most 5 matching documents (or more precisely, a cursor to
those documents).
The matching documents will return with only the _id, name and address fields.
11
MongoDB CRUD Operations
MongoDB Queries
Query Behavior
MongoDB queries exhibit the following behavior:
• All queries in MongoDB address a single collection.
• You can modify the query to impose limits, skips, and sort orders.
• The order of documents returned by a query is not defined unless you specify
a sort().
• Operations that modify existing documents (i.e. updates) use the same query
syntax as queries to select documents to update.
MongoDB provides a db.collection.findOne() method as a special case of find() that
returns a single document.
12
MongoDB CRUD Operations
MongoDB Queries
Query Statements
In the diagram, the query selects documents from the users collection. Using a query
selection operator to define the conditions for matching documents, the query selects
documents that have age greater than (i.e. $gt) 18. Then the sort() modifier sorts the
results by age in ascending order.
13
MongoDB CRUD Operations
MongoDB Queries
Projection
Queries in MongoDB return all fields in all matching documents by default. To limit
the amount of data that MongoDB sends to applications, include a projection in the
queries. By projecting results with a subset of fields, applications reduce their
network overhead and processing requirements.
Projections, which are the second argument to the find() method, may either specify
a list of fields to return or list fields to exclude in the result documents.
By default, the _id field is included in the results. To suppress the _id field from the
result set, specify _id: 0 in the projection document.
14
MongoDB CRUD Operations
MongoDB Queries
Projection
In the diagram, the query selects from the users collection. The criteria matches the
documents that have age equal to 18. Then the projection specifies that only
the name field should return in the matching documents.
15
MongoDB CRUD Operations
MongoDB Queries
Projection Examples
Exclude One Field From a Result Set
This query selects documents in the records collection that match the
condition { "user_id": {$lt: 42 } }, and uses the projection { "history": 0 } to exclude
the history field from the documents in the result set.
16
MongoDB CRUD Operations
MongoDB Queries
Projection Examples
Return Two fields and the _id Field
This query selects documents in the records collection that match the query {
"user_id": { $lt: 42 } } and uses the projection { "name": 1, "email": 1 } to return just
the _id field (implicitly included), name field, and the email field in the documents in
the result set.
17
MongoDB CRUD Operations
MongoDB Queries
Projection Examples
Return Two Fields and Exclude _id
db.records.find( { "user_id": { $lt: 42} },
{ "_id": 0, "name": 1 , "email": 1 } )
This query selects documents in the records collection that match the
query { "user_id": { $lt:42} }, and only returns the name and email fields in the
documents in the result set.
18
MongoDB CRUD Operations
MongoDB Queries
db.collection.find()
19
MongoDB CRUD Operations
MongoDB Queries
db.collection.find()
20
MongoDB CRUD Operations
MongoDB Queries
Find All Documents in a Collection
The find() method with no parameters returns all documents from a collection and
returns all fields for the documents.
For example, the following operation returns all documents in the respective
collections:
db.students.find()
db.students.find({})
db.books.find()
db.books.find({})
db.scores.find()
db.scores.find({})
21
MongoDB CRUD Operations
MongoDB Queries
Find Documents that Match Query Criteria
To find documents that match a set of selection criteria, call find() with
the <criteria> parameter.
The following operation returns all the documents from the students
collection where birth_year is equal to 1990:
The following operation returns all the documents from the books
collection where publicationYear is equal to 2011:
22
MongoDB CRUD Operations
MongoDB Queries
Find Documents that Match Query Criteria
The following operation returns all the documents from the books collection where a
book contains the tag ‘html’:
db.books.find({“tags”: “html”})
23
MongoDB CRUD Operations
MongoDB Queries
Query Using Operators
The following operation returns all the documents from the students
collection where birth_year is greater or equal to 1990:
The following operation returns all the documents from the books
collection where publicationYear is lower or equal to 2009:
24
MongoDB CRUD Operations
MongoDB Queries
Query Using Operators
http://docs.mongodb.org/manual/reference/operator/query/
25
MongoDB CRUD Operations
MongoDB Queries
Query Using Operators
The following operation returns all the documents from the students
collection where birth_year is equal to 1980 or 1985:
26
MongoDB CRUD Operations
MongoDB Queries
Query Using Operators
The following operation returns all the documents from the books
collection where tags contains “html” or “css”:
27
MongoDB CRUD Operations
MongoDB Queries
Query Using Operators
The following operation returns all the documents from the students
collection where birth_year is between 1990 and 1994:
The following operation returns all the documents from the books
collection where publicationYear is between 1990 and 1994:
28
MongoDB CRUD Operations
MongoDB Queries
Query Using Operators
The following operation returns all the documents from the students
collection where birth_year is between 1990 and 1994:
The following operation returns all the documents from the books
collection where publicationYear is between 1990 and 1994:
29
MongoDB CRUD Operations
MongoDB Queries
Query an Array of Documents
The following operation returns all the documents from the books collection where a
book has exactly 2 authors:
The following operation returns all the documents from the books collection where a
book has exactly 1 author:
30
MongoDB CRUD Operations
MongoDB Queries
Query an Array of Documents
The following operation returns all the documents from the books collection where a
book has exactly 2, 3 or 4 authors:
db.books.find({$or: [{"author": {$size: 2}},
{"author": {$size: 3}},
{"author": {$size: 4}}]})
31
MongoDB CRUD Operations
MongoDB Queries
Query with regular expressions
The following operation returns all the documents from the students
collection where student name starts with vocal:
db.students.find({"firstname": /^[aeiou]/i})
32
MongoDB CRUD Operations
33
MongoDB CRUD Operations
db.collection.update(
<query>,
<update>,
{
upsert: <boolean>,
multi: <boolean>,
writeConcern: <document>
}
))
34
MongoDB CRUD Operations
35
MongoDB CRUD Operations
36
MongoDB CRUD Operations
MongoDB findAndModify
findAndModify
The findAndModify command modifies and returns a single document. By default,
the returned document does not include the modifications made on the update. To
return the document with the modifications made on the update, use the new option.
The command has the following syntax:
{
findAndModify: <string>,
query: <document>,
sort: <document>,
remove: <boolean>,
update: <document>,
new: <boolean>,
fields: <document>,
upsert: <boolean>
}
37
MongoDB CRUD Operations
MongoDB findAndModify
findAndModify
The findAndModify command takes the following fields:
38
MongoDB CRUD Operations
MongoDB findAndModify
findAndModify
The findAndModify command takes the following fields:
39
MongoDB CRUD Operations
MongoDB findAndModify
findAndModify
The findAndModify command takes the following fields:
40
MongoDB CRUD Operations
db.collection.remove(
<query>,
<justOne>
)
41
MongoDB CRUD Operations
db.students.remove( { } )
42
MongoDB CRUD Operations
43