0% found this document useful (0 votes)
9 views

03 - Mongodb - Queries

Uploaded by

emajere
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

03 - Mongodb - Queries

Uploaded by

emajere
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

Introduction to MongoDB

MongoDB CRUD Operations


MongoDB CRUD Operations

MongoDB CRUD Introduction


MongoDB stores data in the form of documents, which are JSON-like field and value
pairs. Documents are analogous to structures in programming languages that
associate keys with values (e.g. dictionaries, hashes, maps, and associative arrays).

Formally, MongoDB documents are BSON documents. BSON is a binary


representation of JSON with additional type information.

3
MongoDB CRUD Operations

MongoDB CRUD Introduction


MongoDB stores all documents in collections. A collection is a group of related
documents that have a set of shared common indexes. Collections are analogous to
a table in relational databases.

4
MongoDB CRUD Operations

MongoDB CRUD Introduction


Queries on MongoDB
In MongoDB a query targets a specific collection of documents. 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. You can optionally modify queries to impose limits, skips, and
sort orders.

5
MongoDB CRUD Operations

MongoDB CRUD Introduction

6
MongoDB CRUD Operations

MongoDB CRUD Introduction


Data Modification on MongoDB
Data modification refers to operations that create, update, or delete data. In
MongoDB, these operations modify the data of a single collection. For the update
and delete operations, you can specify the criteria to select the documents to update
or remove.

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:

The following diagram highlights the components of a MongoDB query operation:

10
MongoDB CRUD Operations

MongoDB Queries
Query Interface

db.users.find( { age: { $gt: 18 } },


{ name: 1, address: 1 } ).limit(5)

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

db.records.find( { "user_id": { $lt: 42 } },


{ "history": 0 } )

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

db.records.find( { "user_id": { $lt: 42 } },


{ "name": 1, "email": 1 } )

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:

db.students.find({ "birth_year": 1990 })

The following operation returns all the documents from the books
collection where publicationYear is equal to 2011:

db.books.find({ “publicationYear": 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:

db.students.find({ "birth_year": {$gte: 1990} })

The following operation returns all the documents from the books
collection where publicationYear is lower or equal to 2009:

db.books.find({ “publicationYear": {$lte: 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:

db.students.find({ "birth_year": {$in:[1980, 1985]} })

db.students.find({ $or: [{“birth_year”: 1980},


{“birth_year”: 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”:

db.books.find({"tags": {$in: ["html", "css"]}})

db.books.find({$or: [{"tags": "html"},


{"tags": "css"} ]})

db.books.find({$and: [{"tags": "html"},


{"tags": "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:

db.students.find({ "birth_year": {$gte: 1990, $lte: 1994}})

The following operation returns all the documents from the books
collection where publicationYear is between 1990 and 1994:

db.books.find({"publicationYear": {$gte: 1990, $lte: 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:

db.students.find({$and: [{"birth_year": {$gte: 1990}},


{"birth_year": {$lte: 1994}}]})

The following operation returns all the documents from the books
collection where publicationYear is between 1990 and 1994:

db.books.find({$and: [{"publicationYear": {$gte: 1990}},


{"publicationYear": {$lte: 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:

db.books.find({“author”: {$size: 2}})

The following operation returns all the documents from the books collection where a
book has exactly 1 author:

db.books.find({“author”: {$size: 1}})

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": {$regex: /^[aeiou]/, $options: 'i'}})

db.students.find({"firstname": {$regex: /^[aeiou]/i}})

db.students.find({"firstname": /^[aeiou]/i})

32
MongoDB CRUD Operations

MongoDB – Update a collection


db.collection.update()
db.collection.update(query, update, options)

Modifies an existing document or documents in a collection. The method can modify


specific fields of an existing document or documents or replace an existing document
entirely, depending on the update parameter.
By default, the update() method updates a single document. Set the Multi
Parameter to update all documents that match the query criteria.

33
MongoDB CRUD Operations

MongoDB – Update a collection


db.collection.update()
The update() method has the following form:

db.collection.update(
<query>,
<update>,
{
upsert: <boolean>,
multi: <boolean>,
writeConcern: <document>
}
))

34
MongoDB CRUD Operations

MongoDB – Update a collection


db.collection.update()

35
MongoDB CRUD Operations

MongoDB – Update a collection


db.collection.update()

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

MongoDB Remove Documents


db.collection.remove()
Removes documents from a collection.
The db.collection.remove() method can have one of two syntaxes.
The remove() method can take a query document and an optional justOne boolean:

db.collection.remove(
<query>,
<justOne>
)

41
MongoDB CRUD Operations

MongoDB Remove Documents


Remove All Documents from a Collection
To remove all documents in a collection, call the remove method with an empty
query document {}. The following operation deletes all documents from the students
collection:

db.students.remove( { } )

This operation is not equivalent to the drop() method.


To remove all documents from a collection, it may be more efficient to use
the drop() method to drop the entire collection, including the indexes, and then
recreate the collection and rebuild the indexes.

42
MongoDB CRUD Operations

MongoDB Remove Documents


Remove All Documents that Match a Condition
To remove the documents that match a deletion criteria, call the remove() method
with the <query>parameter.
The following operation removes all the documents from the
collection products where qty is greater than 20:

db.products.remove( { qty: { $gt: 20 } } )

43

You might also like