MongoDB Tutorails
After reading the official mongoDb documentation, the author sorted out the basic concepts, CRUD, and related operations
Overview
RDBMS | MongoDB |
---|---|
Database | Database |
Table | Collection |
Tuple/Row | Document |
column | Field |
Table Join | Embedded Documents |
Primary Key | Primary Key (Default key _id provided by mongodb itself) |
Command
create databse or return the exists database
use DATABSE_NAME
check the current database
db
check the database lists
show dbs
new created db will not show when you use “show dbs” command, you need to insert at least on document into it
db.movie.insert({“name”: “tutorialspoints”})
dropdatabse
db.dropDatabse()
this will delete the selected databse, it not, it will delete the default ‘test’ databse
create collection
db.createCollection(name, options)
Parameter | Type | Description |
---|---|---|
Name | String | Name of the collection to be created |
Options | Document | (Optional) Specify options about memory size and indexing |
Options parameter is optional, so you need to specify only the name of the collection. Following is the list of options you can use −
Field | Type | Description |
---|---|---|
capped | Boolean | (Optional) If true, enables a capped collection. Capped collection is a fixed size collection that automatically overwrites its oldest entries when it reaches its maximum size. If you specify true, you need to specify size parameter also. |
autoIndexId | Boolean | (Optional) If true, automatically create index on _id field.s Default value is false. |
size | number | (Optional) Specifies a maximum size in bytes for a capped collection. If capped is true, then you need to specify this field also. |
max | number | (Optional) Specifies the maximum number of documents allowed in the capped collection. |
example: db.createCollection(“mycollection”)
check the created collection
show collections
mongodb can create collection automatically, when you insert some document
1
db.tutorialspoint.insert({"name": "tutorialspoint"})
drop collection
db.collection.drop() is used to drop a collection from the database
1
db.COLLECTION_NAME.drop()
Data type
- String
- Integer
- Boolean
- Double
- Min/Max keys: This type is used to compare a value against the lowest and highest BSON elements
- Arrays
- Timestamp
- Object
- Null
- Symbol: This datatype is used identically to a string, however, it’s generally reserved for languages that use a specific symbol type.
- Date
- Object ID: used to store the document’s ID
- Binary data
- Code: use to store JavaScript code into the document
- Regular expression
Document CRUD to Collection
insert method
1
db.COLLECTION_NAME.insert(document)
example:
1
2
3
4
5
6
7
8
9db.mycol.insert({
_id: ObjectId(7df78ad8902c),
title: 'MongoDB Overview',
description: 'MongoDB is no sql database',
by: 'tutorials point',
url: 'http://www.tutorialspoint.com',
keywords: ['mongodb', 'database', 'NoSQL'],
likes: 100
})if we don’t specify the _id parameter, the MongoDB assgin a unique ObjectId for this document, _id is 12 bytes hexadecimal number unique for every document in a collection, 12 bytes are divided as follows:
1
2_id: ObjectId(4 bytes timestamp, 3 bytes machine id, 2 bytes process id,
3 bytes incrementer)insert multiple
To insert multiple documents in a single query, we can pass an array of documents in insert command
example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27db.post.insert([
{
title: 'MongoDB Overview',
description: 'MongoDB is no sql database',
by: 'tutorials point',
url: 'http://www.tutorialspoint.com',
keywords: ['mongodb', 'database', 'NoSQL'],
likes: 100
},
{
title: 'NoSQL Database',
description: "NoSQL database doesn't have tables",
by: 'tutorials point',
url: 'http://www.tutorialspoint.com',
keywords: ['mongodb', 'database', 'NoSQL'],
likes: 20,
comments: [
{
user:'user1',
message: 'My first comment',
dateCreated: new Date(2013,11,10,2,35),
like: 0
}
]
}
])To insert the document you can also use db.COLLECTION_NAME.save .
But if you specify the _id, it will replace the whole data with the specified _id
Query document
1
db.COLLECTION_NAME.find()
find() method will display all documents in a non-structured way
if you want to display the result in a formatted way, we can use pretty method
1
db.COLLECTION_NAME.find().pretty()
Operation Syntax Example RDBMS Equivalent Equality { : } db.mycol.find({“by”:“tutorials point”}).pretty() where by = ‘tutorials point’ Less Than { :{$lt: }} db.mycol.find({“likes”:{$lt:50}}).pretty() where likes < 50 Less Than Equals { :{$lte: }} db.mycol.find({“likes”:{$lte:50}}).pretty() where likes <= 50 Greater Than { :{$gt: }} db.mycol.find({“likes”:{$gt:50}}).pretty() where likes > 50 Greater Than Equals { :{$gte: }} db.mycol.find({“likes”:{$gte:50}}).pretty() where likes >= 50 Not Equals { :{$ne: }} db.mycol.find({“likes”:{$ne:50}}).pretty() where likes != 50 AND in the find method, if you pass multiple keys by separating them by ‘,’, then mongoDB treats it as AND condition, following is the basic syntax of and. example:
1
db.mycol.find({$and:[{"by":"tutorials point"},{"title": "MongoDB Overview"}]}).pretty()
OR example:
1
db.mycol.find({$or:[{"by":"tutorials point"},{"title": "MongoDB Overview"}]}).pretty()
USE AND and OR together
1
db.mycol.find({"likes": {$gt:10}, $or: [{"by": "tutorials point"},
Equivalent SQL where clause is ‘where likes>10 AND (by = ‘tutorials point’ OR title = ‘MongoDB Overview’)’
Update Document
1
db.COLLECTION_NAME.update(SELECTION_CRITERIA, UPDATED_DATA)
example:
1
db.mycol.update({'title':'MongoDB Overview'},{$set:{'title':'New MongoDB Tutorial'}})
by default, MongoDB will update only a single document, To update multiple documents, you need to set a parameter ‘multi’ to true, example:
1
db.mycol.update({'title':'MongoDB Overview'},{$set:{'title':'New MongoDB Tutorial'}},{multi:true})
save method can also update the data
1
db.COLLECTION_NAME.save({_id:ObjectId(),NEW_DATA})
example:
1
2
3
4
5
6db.mycol.save(
{
"_id" : ObjectId(5983548781331adf45ec5), "title":"Tutorials Point New Topic",
"by":"Tutorials Point"
}
)Delete Document
MongoDB’s remove() method is used to remove a document from the collection. remove() method accepts two parameters. One is deletion criteria and second is justOne flag.
1
2
3db.COLLECTION_NAME.remove(DELLETION_CRITTERIA) //remove sepecified
db.COLLECTION_NAME.remove(DELETION_CRITERIA,1) //remove one
db.mycol.remove({}) //remove allexample:
1
db.mycol.remove({'title':'MongoDB Overview'})
Projection
In the MongoDB, projection means selecting only the necessary data rather than selecting whole of the data of a document.
MongoDB’s find method accept second optional parameter that is list of fields that you want to retrieve. In MongoDB, we can set a list of fields with value 1 or 0, 1 is used to show the fields
1 | db.COLLECTION_NAME.find({},{KEY: 1}) |
Limiting
limit method accept one number type argument, which is the number of documents that you want to display
1 | db.COLLECTION_NAME.find().limit(NUMBER) |
skip method can accept number type argument and is used to skip the number of documents
1 | db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER) |
example: following example will display only the second document
1 | db.mycol.find({}, {"title": 1, _id: 0}).limit(1).skip(1) |
Sorting
sort method accepts a document containing a list of fields along with their sorting order. To specify sorting order 1 and -1 are used. 1 is used for ascending order while -1 is used for descending order.(default ascending order)
1 | db.COLLECTION_NAME.find().sort({KEY:1}) |
example:
1 | db.mycol.find({},{"title":1,_id:0}).sort({"title":-1}) |
Indexing
indexing support the efficient resolution of queries. Without indexes, MongoDB must scan every document of a collection to select those documents that match the query statement.
Indexes are special data structures, that store a small portion of data set in an easy-to-traverse form. The index stores the value of a specific field or set of fields, ordered by the value of the field as specified in the index.
Syntax:
1 | db.COLLECTION_NAME.ensureIndex({KEY: 1}) |
key is the name of the field on which you want to create index and 1 is for ascending order
example:
1 | db.mycol.ensureIndex({"title":1}) |
we can also specify multiple fields:
1 | db.mycol.ensureIndex({"title":1,"description":-1}) |
Parameter | Type | Description |
---|---|---|
background | Boolean | Builds the index in the background so that building an index does not block other database activities. Specify true to build in the background. The default value is false. |
unique | Boolean | Creates a unique index so that the collection will not accept insertion of documents where the index key or keys match an existing value in the index. Specify true to create a unique index. The default value is false. |
name | string | The name of the index. If unspecified, MongoDB generates an index name by concatenating the names of the indexed fields and the sort order. |
dropDups | Boolean | Creates a unique index on a field that may have duplicates. MongoDB indexes only the first occurrence of a key and removes all documents from the collection that contain subsequent occurrences of that key. Specify true to create unique index. The default value is false. |
sparse | Boolean | If true, the index only references documents with the specified field. These indexes use less space but behave differently in some situations (particularly sorts). The default value is false. |
expireAfterSeconds | integer | Specifies a value, in seconds, as a TTL to control how long MongoDB retains documents in this collection. |
v | index version | The index version number. The default index version depends on the version of MongoDB running when creating the index. |
weights | document | The weight is a number ranging from 1 to 99,999 and denotes the significance of the field relative to the other indexed fields in terms of the score. |
default_language | string | For a text index, the language that determines the list of stop words and the rules for the stemmer and tokenizer. The default value is english. |
language_override | string | For a text index, specify the name of the field in the document that contains, the language to override the default language. The default value is language. |
Aggregate
Aggregate operations process data records and return computed results. Aggregate operations group values from multiple documents together, and can perform a variety of operations on the grouped data to return a single result. In SQL count(*) and with group by is an equivalent of mongodb aggregation
Syntax
1 | db.COLLECTION_NAME.aggreagate(AGGREGATE_OPERATION) |
example:
if we have the following data
1 | { |
if we want to display a list stating how many tutorials are written by each user
1 | db.mycol.aggregate([{$group: {_id: '$by_user', num_tutorial: {$sum: 1}}}]) |
is equal to select by_user, count(*) from mycol group by by_user.
in the above example, we have grouped documents by fields by_user and on each occurrence of by_user previous value of sum is incremented. Following is a list of available aggregation expressions.
Expression | Description | Example |
---|---|---|
$sum | Sums up the defined value from all documents in the collection. | db.mycol.aggregate([{group : {_id : "by_user", num_tutorial : {likes"}}}]) |
$avg | Calculates the average of all given values from all documents in the collection. | db.mycol.aggregate([{group : {_id : "by_user", num_tutorial : {likes"}}}]) |
$min | Gets the minimum of the corresponding values from all documents in the collection. | db.mycol.aggregate([{group : {_id : "by_user", num_tutorial : {likes"}}}]) |
$max | Gets the maximum of the corresponding values from all documents in the collection. | db.mycol.aggregate([{group : {_id : "by_user", num_tutorial : {likes"}}}]) |
$push | Inserts the value to an array in the resulting document. | db.mycol.aggregate([{group : {_id : "by_user", url : {url"}}}]) |
$addToSet | Inserts the value to an array in the resulting document but does not create duplicates. | db.mycol.aggregate([{group : {_id : "by_user", url : {url"}}}]) |
$first | Gets the first document from the source documents according to the grouping. Typically this makes only sense together with some previously applied “$sort”-stage. | db.mycol.aggregate([{group : {_id : "by_user", first_url : {url"}}}]) |
$last | Gets the last document from the source documents according to the grouping. Typically this makes only sense together with some previously applied “$sort”-stage. | db.mycol.aggregate([{group : {_id : "by_user", last_url : {url"}}}]) |
Pipeline Concept
In UNIX command, shell pipeline means the possibility to execute an operation on some input and use the output as the input for the next command and so on. MongoDB also supports same concept in aggregation framework. There is a set of possible stages and each of those is taken as a set of documents as an input and produces a resulting set of documents (or the final resulting JSON document at the end of the pipeline). This can then in turn be used for the next stage and so on.
Following are the possible stages in aggregation framework −
- $project − Used to select some specific fields from a collection.
- $match − This is a filtering operation and thus this can reduce the amount of documents that are given as input to the next stage.
- $group − This does the actual aggregation as discussed above.
- $sort − Sorts the documents.
- $skip − With this, it is possible to skip forward in the list of documents for a given amount of documents.
- $limit − This limits the amount of documents to look at, by the given number starting from the current positions.
- $unwind − This is used to unwind document that are using arrays. When using an array, the data is kind of pre-joined and this operation will be undone with this to have individual documents again. Thus with this stage we will increase the amount of documents for the next stage.
Replication
Replication is the process of synchronizing data across multiple servers. Replication provides redundancy and increases data availability with multiple copies of data on different database servers. Replication protects a database from the loss of a single server. Replication also allows you to recover from hardware failure and service interruptions. With additional copies of the data, you can dedicate one to disaster recovery, reporting, or backup.
MongoDB achieves replication by the use of replica set. A replica set is a group of mongod instances that host the same data set. In a replica, one node is primary node that receives all write operations. All other instances, such as secondaries, apply operations from the primary so that they have the same data set. Replica set can have only one primary node.
- Replica set is a group of two or more nodes (generally minimum 3 nodes are required).
- In a replica set, one node is primary node and remaining nodes are secondary.
- All data replicates from primary to secondary node.
- At the time of automatic failover or maintenance, election establishes for primary and a new primary node is elected.
- After the recovery of failed node, it again join the replica set and works as a secondary node.
Set Up a Replica Set
In this tutorial, we will convert standalone MongoDB instance to a replica set. To convert to replica set, following are the steps −
- Shutdown already running MongoDB server.
- Start the MongoDB server by specifying – replSet option. Following is the basic syntax of --replSet −
1 | mongod --port "PORT" --dbpath "YOUR_DB_DATA_PATH" --replSet "REPLICA_SET_INSTANCE_NAME" |
Example
1 | mongod --port 27017 --dbpath "D:\set up\mongodb\data" --replSet rs0 |
- It will start a mongod instance with the name rs0, on port 27017.
- Now start the command prompt and connect to this mongod instance.
- In Mongo client, issue the command rs.initiate() to initiate a new replica set.
- To check the replica set configuration, issue the command rs.conf(). To check the status of replica set issue the command rs.status().
Add Members to Replica Set
To add members to replica set, start mongod instances on multiple machines. Now start a mongo client and issue a command rs.add().
Syntax
The basic syntax of rs.add() command is as follows −
1 | >rs.add(HOST_NAME:PORT) |
Example
Suppose your mongod instance name is mongod1.net and it is running on port 27017. To add this instance to replica set, issue the command rs.add() in Mongo client.
1 | >rs.add("mongod1.net:27017") |
You can add mongod instance to replica set only when you are connected to primary node. To check whether you are connected to primary or not, issue the command db.isMaster() in mongo client.