Teach you the installation and detailed use of MongoDB (2)

The previous article practiced, the following operations of MongoDB

  • Install the MongoDB service
  • Connect to MongoDB
  • MongoDB create database
  • MongoDB delete database
  • MongoDB insert document
  • MongoDB delete document
  • MongoDB query document
  • MongoDB AND condition
  • MongoDB OR 条件
  • MongoDB AND and OR use in conjunction
  • MongoDB conditional operators
  • MongoDB (>) greater than operator - $gt
  • MongoDB (>=) greater than or equal operator - $gte
  • MongoDB (<) less than operator - $lt
  • MongoDB (<=) less than operator - $lte
  • MongoDB queries with (<) and (>) - $lt and $gt

Teach you the installation and detailed use of MongoDB (1)

http://www.ymq.io/2018/01/29/MongoDB-2/

continue next

  1. MongoDB Limit and Skip method
  2. MongoDB sort
  3. MongoDB indexes
  4. MongoDB aggregation
  5. MongoDB master-slave replication (replica set)
  6. MongoDB automatic failover

1. MongoDB Limit and Skip method

Limit() method

MongoDB Limit() method

If you need to read a specified number of data records in MongoDB, you can use MongoDB's Limit method. The limit() method accepts a numeric parameter that specifies the number of records to read from MongoDB.

Insert test data

db.col.insert({title: 'MongoDB-1'})
db.col.insert({title: 'MongoDB-2'})
db.col.insert({title: 'MongoDB-3'})
db.col.insert({title: 'MongoDB-4'})
MongoDB Enterprise > db.col.find()
{ "_id" : ObjectId("5a6e8eaef14a3f270ba2dd0c"), "title" : "MongoDB-1" }
{ "_id" : ObjectId("5a6e8ec8f14a3f270ba2dd0d"), "title" : "MongoDB-2" }
{ "_id" : ObjectId("5a6e8ecbf14a3f270ba2dd0e"), "title" : "MongoDB-3" }
{ "_id" : ObjectId("5a6e8ed5f14a3f270ba2dd0f"), "title" : "MongoDB-4" }
MongoDB Enterprise >

grammar

The basic syntax of the limit() method is as follows:

> db.COLLECTION_NAME.find().limit(NUMBER)

The above example shows two records in the query document:

MongoDB Enterprise > db.col.find().limit(2)
{ "_id" : ObjectId("5a6e8eaef14a3f270ba2dd0c"), "title" : "MongoDB-1" }
{ "_id" : ObjectId("5a6e8ec8f14a3f270ba2dd0d"), "title" : "MongoDB-2" }
MongoDB Enterprise > db.col.find({},{"title":1,_id:0}).limit(2)
{ "title" : "MongoDB-1" }
{ "title" : "MongoDB-2" }
MongoDB Enterprise >

Note: If you do not specify parameters in the limit() method, all data in the collection will be displayed.

MongoDB Enterprise > db.col.find({},{"title":1,_id:0}).limit()
{ "title" : "MongoDB-1" }
{ "title" : "MongoDB-2" }
{ "title" : "MongoDB-3" }
{ "title" : "MongoDB-4" }

Skip() method

In addition to using the limit() method to read the specified amount of data, we can also use the skip() method to skip the specified amount of data. The skip method also accepts a numeric parameter as the number of records to skip. grammar

The syntax of the skip() method script is as follows:

> db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER)

example

The above example will only display the second document data

MongoDB Enterprise > db.col.find({},{"title":1,_id:0}).limit(1).skip(1)
{ "title" : "MongoDB-2" }
MongoDB Enterprise >

Note: The default parameter of skip() method is 0

2. MongoDB sorting

MongoDB sort() method

Use the sort() method to sort data in MongoDB, and the sort() method can specify the sorted fields through parameters

Use 1 and -1 to specify how to sort, where 1 is for ascending order and -1 is for descending order.

grammar

The basic syntax of the sort() method is as follows:

> db.COLLECTION_NAME.find().sort({KEY:1})

The data in the col collection is as follows:

MongoDB Enterprise > db.col.find()
{ "_id" : ObjectId("5a6e8eaef14a3f270ba2dd0c"), "title" : "MongoDB-1" }
{ "_id" : ObjectId("5a6e8ec8f14a3f270ba2dd0d"), "title" : "MongoDB-2" }
{ "_id" : ObjectId("5a6e8ecbf14a3f270ba2dd0e"), "title" : "MongoDB-3" }
{ "_id" : ObjectId("5a6e8ed5f14a3f270ba2dd0f"), "title" : "MongoDB-4" }
MongoDB Enterprise >

where 1 is for ascending order, and -1 is for descending order

The following example demonstrates that the data in the col collection is sorted in descending order by the field title:

MongoDB Enterprise > db.col.find({},{"title":1,_id:0}).sort({"title":-1})
{ "title" : "MongoDB-4" }
{ "title" : "MongoDB-3" }
{ "title" : "MongoDB-2" }
{ "title" : "MongoDB-1" }
MongoDB Enterprise >

Note: If the sorting method of the sort() method is not specified, the documents are sorted in ascending order by default.

3. MongoDB indexes

Indexes can usually greatly improve the efficiency of queries. Without indexes, MongoDB must scan each file in the collection and select those records that meet the query conditions when reading data.

The query efficiency of scanning the entire collection is very low, especially when processing a large amount of data, the query can take tens of seconds or even several minutes, which is very fatal to the performance of the website.

An index is a special data structure that is stored in a collection of data that is easy to traverse and read. An index is a structure that sorts the values ​​of one or more columns in a database table

ensureIndex() method

MongoDB uses the ensureIndex() method to create indexes.

grammar

The basic syntax of the ensureIndex() method is as follows:

> db.COLLECTION_NAME.ensureIndex({KEY:1})

The Key value in the syntax is the index field you want to create, 1 is to specify the index to be created in ascending order, and -1 can be specified if you want to create the index in descending order.

example

> db.COLLECTION_NAME.ensureIndex({KEY:1})

The Key value in the syntax is the index field you want to create, 1 is to specify the index to be created in ascending order, and -1 can be specified if you want to create the index in descending order.

example

MongoDB Enterprise > db.col.ensureIndex({"title":1})
{
	"createdCollectionAutomatically" : false,
	"numIndexesBefore" : 1,
	"numIndexesAfter" : 2,
	"ok" : 1
}
MongoDB Enterprise > 
db.col.insert({title: 'MongoDB 教程', 
    description: 'MongoDB 是一个 Nosql 数据库',
    by: '搜云库教程-专注于开发技术的研究与知识分享',
    url: 'http://www.souyunku.com',
    tags: ['mongodb', 'database', 'NoSQL'],
    likes: 100
})

In the ensureIndex() method, you can also set up an index with multiple fields (called a compound index in relational databases).

MongoDB Enterprise > db.col.ensureIndex({"title":1,"description":1})
{
	"createdCollectionAutomatically" : false,
	"numIndexesBefore" : 3,
	"numIndexesAfter" : 4,
	"ok" : 1
}

ensureIndex() accepts optional parameters. The list of optional parameters is as follows:

example

Create an index in the background:

The indexing process will block other database operations. Background can be specified to create indexes in the background, that is, add the "background" optional parameter. "background" defaults to false.

MongoDB Enterprise > db.col.ensureIndex({"url":1}, {background: true})
{
	"createdCollectionAutomatically" : false,
	"numIndexesBefore" : 5,
	"numIndexesAfter" : 6,
	"ok" : 1
}
MongoDB Enterprise > 

4. MongoDB Aggregation

MongoDB aggregation

Aggregates in MongoDB are mainly used to process data (such as statistical average, summation, etc.) and return the calculated data results. Somewhat similar to count(*) in SQL statements.

aggregate() method

Delete previous test data

MongoDB Enterprise > db.col.remove({})
WriteResult({ "nRemoved" : 5 })
MongoDB Enterprise >

Insert new test data

db.col.insert({
	title: 'MongoDB 教程',
	description: 'MongoDB 是一个 Nosql 数据库',
	by_user: 'penglei',
	url: 'http://www.souyunku.com',
	tags: ['mongodb', 'database', 'NoSQL'],
	likes: 100
})
db.col.insert({
	title: 'MongoDB 教程',
	description: 'MongoDB 是一个 Nosql 数据库',
	by_user: 'penglei',
	url: 'http://www.souyunku.com',
	tags: ['mongodb', 'database', 'NoSQL'],
	likes: 200
})
db.col.insert({
	title: 'MongoDB 教程',
	description: 'MongoDB 是一个 Nosql 数据库',
	by_user: 'penglei',
	url: 'http://www.souyunku.com',
	tags: ['mongodb', 'database', 'NoSQL'],
	likes: 300
})
MongoDB Enterprise > db.col.find()
{ "_id" : ObjectId("5a6ebfab5326a260464a4072"), "title" : "MongoDB 教程", "description" : "MongoDB 是一个 Nosql 数据库", "by_user" : "penglei", "url" : "http://www.souyunku.com", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100 }
{ "_id" : ObjectId("5a6ebfab5326a260464a4073"), "title" : "MongoDB 教程", "description" : "MongoDB 是一个 Nosql 数据库", "by_user" : "penglei", "url" : "http://www.souyunku.com", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 200 }
{ "_id" : ObjectId("5a6ebfab5326a260464a4074"), "title" : "MongoDB 教程", "description" : "MongoDB 是一个 Nosql 数据库", "by_user" : "penglei", "url" : "http://www.souyunku.com", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 300 }
MongoDB Enterprise > 

The method of aggregation in MongoDB uses aggregate().

grammar

The basic syntax format of the aggregate() method is as follows:

> db.COLLECTION_NAME.aggregate(AGGREGATE_OPERATION)

MongoDB Enterprise > db.col.aggregate([{$group : {_id : "$by_user", num_tutorials : {$sum : 1}}}])
{
	"_id": "penglei",
	"num_tutorials": 3
}
MongoDB Enterprise > db.col.aggregate([{$group : {_id : "$by_user", totle : {$sum : 1}}}])
{
	"_id": "penglei",
	"totle": 3
}
MongoDB Enterprise > 

The above example is similar to the sql statement:select by_user, count(*) from col group by by_user

In the above example, we group the data by the field by_user field and calculate the sum of the same values ​​of the by_user field.

The following table shows some aggregate expressions:

pipe concept

Pipes are commonly used in Unix and Linux to pass the output of the current command as an argument to the next command.

MongoDB's aggregation pipeline takes MongoDB documents after processing one pipeline and passes the result to the next pipeline for processing. Pipeline operations are repeatable.

Expression: Process the input document and output it. Expressions are stateless and can only be used to evaluate documents in the current aggregation pipeline, not other documents.

Here we introduce several operations commonly used in the aggregation framework:

  • $project: Modify the structure of the input document. Can be used to rename, add or delete fields, and can also be used to create calculated results and nested documents.
  • $match: Used to filter data and only output documents that meet the conditions. $match uses MongoDB's standard query operations.
  • $limit: Used to limit the number of documents returned by the MongoDB aggregation pipeline.
  • $skip: Skip the specified number of documents in the aggregation pipeline and return the remaining documents.
  • $unwind: Splits an array type field in the document into multiple entries, each containing a value in the array.
  • $group: Groups the documents in the collection, which can be used for statistical results.
  • $sort: Sort the input documents and output them.
  • $geoNear: Output ordered documents close to a geographic location.

Example of the pipe operator

1. $project instance

MongoDB Enterprise > db.col.aggregate(
    { $project : {
        title : 1 ,
        by_user : 1 ,
    }}
 );
 
{ "_id" : ObjectId("5a6ebfab5326a260464a4072"), "title" : "MongoDB 教程", "by_user" : "penglei" }
{ "_id" : ObjectId("5a6ebfab5326a260464a4073"), "title" : "MongoDB 教程", "by_user" : "penglei" }
{ "_id" : ObjectId("5a6ebfab5326a260464a4074"), "title" : "MongoDB 教程", "by_user" : "penglei" }
MongoDB Enterprise > 

In this case, there are only three fields _id, tilte and by_user in the result. By default, the _id field is included. If you want to exclude _id, you can do this:

MongoDB Enterprise > db.col.aggregate(
    { $project : {
        _id : 0 ,
        title : 1 ,
        by_user : 1
    }});
{ "title" : "MongoDB 教程", "by_user" : "penglei" }
{ "title" : "MongoDB 教程", "by_user" : "penglei" }
{ "title" : "MongoDB 教程", "by_user" : "penglei" }

2. $match instance

db.col.aggregate( [
				{ $match : { likes : { $gt : 90, $lte : 200 } } },
				{ $group: { _id: null, count: { $sum: 1 } } }
			   ] );

$match is used to obtain records with likes greater than 70 and less than or equal to 90, and then send the eligible records to the next stage $group pipeline operator for processing.

MongoDB Enterprise > db.col.aggregate([{$group : {_id : "$by_user", num_tutorial : {$sum : 1}}}])
{ "_id" : "penglei", "num_tutorial" : 3 }
MongoDB Enterprise >

The above example is similar to the sql statement:

select by_user as _id, count(*) as num_tutorial from mycol group by by_user

Aggregate operations by day, month, year, week, hour, and minute are as follows:

db.getCollection('m_msg_tb').aggregate(
[
    {$match:{m_id:10001,mark_time:{$gt:new Date(2017,8,0)}}},
    {$group: {
       _id: {$dayOfMonth:'$mark_time'},
        pv: {$sum: 1}
        }
    },
    {$sort: {"_id": 1}}
])

The time keywords are as follows:

  • $dayOfYear: Returns the day of the year that the date is (366 days in a year).
  • $dayOfMonth: Returns the day of the month (1 to 31) that the date is.
  • $dayOfWeek: Returns the day of the week (1: Sunday, 7: Saturday).
  • $year: Returns the year part of the date.
  • $month: Returns the month portion of the date (1 to 12).
  • $week: Returns the week of the year (0 to 53) that the date is in.
  • $hour: Returns the hour portion of the date.
  • $minute: Returns the minute part of the date.
  • $second: Returns the second part of the date (returns the second part of the date as a number between 0 and 59, but can be 60 to account for leap seconds).
  • $millisecond: Returns the millisecond portion of the date (0 to 999).
  • $dateToString: { $dateToString: { format: , date: } }。

5. MongoDB master-slave replication (replica set)

MongoDB replication is the process of synchronizing data across multiple servers.

Replication provides redundant backup of data and stores data copies on multiple servers, which improves data availability and ensures data security.

Replication also allows you to recover data from hardware failures and service interruptions.

Official documentation https://docs.mongodb.com/manual/replication/

5.1 What is replication?

  • Ensure data security
  • Data High Availability (24*7)
  • disaster recovery
  • No downtime for maintenance (eg backups, reindexing, compression)
  • Distributed read data

5.2 MongoDB Replication Principle

Replication of mongodb requires at least two nodes. One of them is the master node, which is responsible for processing client requests, and the rest are slave nodes, which are responsible for replicating the data on the master node.

The common collocation methods of mongodb nodes are: one master and one slave, one master and multiple slaves.

The master node records all operations oplogs on it, and the slave node periodically polls the master node to obtain these operations, and then performs these operations on its own data copy, thereby ensuring that the slave node's data is consistent with the master node.

The MongoDB replication structure diagram is as follows:

In the above structure diagram, the client reads data from the master node, and when the client writes data to the master node, the master node and the slave node perform data interaction to ensure data consistency.

5.3 Replica Set Characteristics

  • A cluster of N nodes
  • Any node can be the master node
  • All writes are on the primary node
  • automatic failover
  • Automatic recovery

5.4 MongoDB replica set settings

1. Shut down the running MongoDB server.

service mongod stop

2. Node establishment

First of all, you need to go to the folder where the mongodb data file you choose is stored and create three new databases to simulate three unconnected machines. The path of the blogger is as follows

mkdir -p /data/db/node1
mkdir -p /data/db/node2
mkdir -p /data/db/node3

3. Start three databases (dbpath), and the port (--port 1000x), cluster name (--replSet gabriel), close the log option (--nojournal), start the daemon process, it will be automatically pulled (--fork ), log directory (--logpath)

mongod --dbpath /data/db/node1 --port 10001 --replSet gabriel --nojournal --fork --logpath /data/db/node1.log
mongod --dbpath /data/db/node2 --port 10002 --replSet gabriel --nojournal --fork --logpath /data/db/node2.log
mongod --dbpath /data/db/node3 --port 10003 --replSet gabriel --nojournal --fork --logpath /data/db/node3.log

4. By the way, connect to a server and do the initialization operation. Here the blogger connects to port 10001

Enter under the terminal

mongo localhost:10001

Enter the initialization method after entering

MongoDB Enterprise gabriel:OTHER> rs.initiate({_id:"gabriel",members:[
{_id:1,host:"localhost:10001"},
{_id:2,host:"localhost:10002"},
{_id:3,host:"localhost:10003"},
]})

The following information is received and it is successful.

{
	"ok" : 1,
	"operationTime" : Timestamp(1517221411, 1),
	"$clusterTime" : {
		"clusterTime" : Timestamp(1517221411, 1),
		"signature" : {
			"hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
			"keyId" : NumberLong(0)
		}
	}
}
MongoDB Enterprise gabriel:OTHER>

At this point you will find that the output on the terminal has changed.

//从单个一个
>
//变成了
gabriel:OTHER>

5. Query status

MongoDB Enterprise gabriel:OTHER> rs.status()
{
	"set" : "gabriel",
	"date" : ISODate("2018-01-29T10:33:21.227Z"),
	"myState" : 1,
	"term" : NumberLong(1),
	"heartbeatIntervalMillis" : NumberLong(2000),
	"optimes" : {
		"lastCommittedOpTime" : {
			"ts" : Timestamp(1517221984, 1),
			"t" : NumberLong(1)
		},
		"readConcernMajorityOpTime" : {
			"ts" : Timestamp(1517221984, 1),
			"t" : NumberLong(1)
		},
		"appliedOpTime" : {
			"ts" : Timestamp(1517221994, 1),
			"t" : NumberLong(1)
		},
		"durableOpTime" : {
			"ts" : Timestamp(1517221994, 1),
			"t" : NumberLong(1)
		}
	},
	"members" : [
		{
			"_id" : 1,
			"name" : "localhost:10001",
			"health" : 1,
			"state" : 1,
			"stateStr" : "PRIMARY",
			"uptime" : 659,
			"optime" : {
				"ts" : Timestamp(1517221994, 1),
				"t" : NumberLong(1)
			},
			"optimeDate" : ISODate("2018-01-29T10:33:14Z"),
			"electionTime" : Timestamp(1517221422, 1),
			"electionDate" : ISODate("2018-01-29T10:23:42Z"),
			"configVersion" : 1,
			"self" : true
		},
		{
			"_id" : 2,
			"name" : "localhost:10002",
			"health" : 1,
			"state" : 2,
			"stateStr" : "SECONDARY",
			"uptime" : 589,
			"optime" : {
				"ts" : Timestamp(1517221994, 1),
				"t" : NumberLong(1)
			},
			"optimeDurable" : {
				"ts" : Timestamp(1517221984, 1),
				"t" : NumberLong(1)
			},
			"optimeDate" : ISODate("2018-01-29T10:33:14Z"),
			"optimeDurableDate" : ISODate("2018-01-29T10:33:04Z"),
			"lastHeartbeat" : ISODate("2018-01-29T10:33:20.972Z"),
			"lastHeartbeatRecv" : ISODate("2018-01-29T10:33:19.923Z"),
			"pingMs" : NumberLong(0),
			"syncingTo" : "localhost:10001",
			"configVersion" : 1
		},
		{
			"_id" : 3,
			"name" : "localhost:10003",
			"health" : 1,
			"state" : 2,
			"stateStr" : "SECONDARY",
			"uptime" : 589,
			"optime" : {
				"ts" : Timestamp(1517221994, 1),
				"t" : NumberLong(1)
			},
			"optimeDurable" : {
				"ts" : Timestamp(1517221984, 1),
				"t" : NumberLong(1)
			},
			"optimeDate" : ISODate("2018-01-29T10:33:14Z"),
			"optimeDurableDate" : ISODate("2018-01-29T10:33:04Z"),
			"lastHeartbeat" : ISODate("2018-01-29T10:33:20.972Z"),
			"lastHeartbeatRecv" : ISODate("2018-01-29T10:33:19.921Z"),
			"pingMs" : NumberLong(0),
			"syncingTo" : "localhost:10001",
			"configVersion" : 1
		}
	],
	"ok" : 1,
	"operationTime" : Timestamp(1517221994, 1),
	"$clusterTime" : {
		"clusterTime" : Timestamp(1517221994, 1),
		"signature" : {
			"hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
			"keyId" : NumberLong(0)
		}
	}
}

In the return, the parameter set is followed by the cluster name, and each member can see their respective situations, where stateStr is the role, and the primary node is (PRIMARY).

6. Enter the master node to insert data, enter the slave node to view the data

The main node of the blogger is on the 10001 interface

mongo localhost:10001

insert data

MongoDB Enterprise gabriel:PRIMARY> use test
switched to db test
db.col.insert({title: 'MongoDB 教程', 
    description: 'MongoDB 是一个 Nosql 数据库',
    by: '搜云库教程-专注于开发技术的研究与知识分享',
    url: 'http://www.souyunku.com',
    tags: ['mongodb', 'database', 'NoSQL'],
    likes: 100
})
MongoDB Enterprise gabriel:PRIMARY> db.col.find()
{ "_id" : ObjectId("5a6ef998525d903d07a00cdf"), "title" : "MongoDB 教程", "description" : "MongoDB 是一个 Nosql 数据库", "by" : "搜云库教程-专注于开发技术的研究与知识分享", "url" : "http://www.souyunku.com", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100 }
MongoDB Enterprise gabriel:PRIMARY> 

The blogger switches from node 10002

mongo localhost:10002

Switch to the slave node, you will find that an error will be reported when using show dbs, because the permission has not been enabled, enter rs.slaveOk(); and you can access it smoothly.

MongoDB Enterprise gabriel:SECONDARY> show dbs
2018-01-29T10:40:37.362+0000 E QUERY    [thread1] Error: listDatabases failed:{
	"operationTime" : Timestamp(1517222434, 1),
	"ok" : 0,
	"errmsg" : "not master and slaveOk=false",
	"code" : 13435,
	"codeName" : "NotMasterNoSlaveOk",
	"$clusterTime" : {
		"clusterTime" : Timestamp(1517222434, 1),
		"signature" : {
			"hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
			"keyId" : NumberLong(0)
		}
	}
} :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
Mongo.prototype.getDBs@src/mongo/shell/mongo.js:65:1
shellHelper.show@src/mongo/shell/utils.js:813:19
shellHelper@src/mongo/shell/utils.js:703:15
@(shellhelp2):1:1
MongoDB Enterprise gabriel:SECONDARY> 
MongoDB Enterprise gabriel:SECONDARY> rs.slaveOk()

check again

MongoDB Enterprise gabriel:SECONDARY> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB
test    0.000GB
MongoDB Enterprise gabriel:SECONDARY> 

Switch to the test library and check that the data has been synchronized

MongoDB Enterprise gabriel:SECONDARY> use test
switched to db test
MongoDB Enterprise gabriel:SECONDARY> db.col.find()
{ "_id" : ObjectId("5a6ef998525d903d07a00cdf"), "title" : "MongoDB 教程", "description" : "MongoDB 是一个 Nosql 数据库", "by" : "搜云库教程-专注于开发技术的研究与知识分享", "url" : "http://www.souyunku.com", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100 }
MongoDB Enterprise gabriel:SECONDARY> 

The above is a simple master-slave replication establishment process. Now the data inserted by the master server can be seen on the slave server.

Switching from node 10003 same problem

delete slave node

rs.remove('ip:port')

After shutting down the master server and restarting it, you will find that the original slave server has become a slave server, and the newly started server (original slave server) has become a slave server

6. MongoDB Automatic Failover

First of all, by rs.status()checking , you can see that the master node is 10001, and the master node "name" : "localhost:10001", "stateStr" : "PRIMARY"next stops the 10001 master node to test the failover

MongoDB Enterprise gabriel:PRIMARY>  rs.status()
{
	"set" : "gabriel",
	"date" : ISODate("2018-01-30T02:39:58.468Z"),
	"myState" : 1,
	"term" : NumberLong(1),
	"heartbeatIntervalMillis" : NumberLong(2000),
	"optimes" : {
		"lastCommittedOpTime" : {
			"ts" : Timestamp(1517279986, 1),
			"t" : NumberLong(1)
		},
		"readConcernMajorityOpTime" : {
			"ts" : Timestamp(1517279986, 1),
			"t" : NumberLong(1)
		},
		"appliedOpTime" : {
			"ts" : Timestamp(1517279996, 1),
			"t" : NumberLong(1)
		},
		"durableOpTime" : {
			"ts" : Timestamp(1517279996, 1),
			"t" : NumberLong(1)
		}
	},
	"members" : [
		{
			"_id" : 1,
			"name" : "localhost:10001",
			"health" : 1,
			"state" : 1,
			"stateStr" : "PRIMARY",
			"uptime" : 58656,
			"optime" : {
				"ts" : Timestamp(1517279996, 1),
				"t" : NumberLong(1)
			},
			"optimeDate" : ISODate("2018-01-30T02:39:56Z"),
			"electionTime" : Timestamp(1517221422, 1),
			"electionDate" : ISODate("2018-01-29T10:23:42Z"),
			"configVersion" : 1,
			"self" : true
		},
		{
			"_id" : 2,
			"name" : "localhost:10002",
			"health" : 1,
			"state" : 2,
			"stateStr" : "SECONDARY",
			"uptime" : 58586,
			"optime" : {
				"ts" : Timestamp(1517279996, 1),
				"t" : NumberLong(1)
			},
			"optimeDurable" : {
				"ts" : Timestamp(1517279986, 1),
				"t" : NumberLong(1)
			},
			"optimeDate" : ISODate("2018-01-30T02:39:56Z"),
			"optimeDurableDate" : ISODate("2018-01-30T02:39:46Z"),
			"lastHeartbeat" : ISODate("2018-01-30T02:39:58.289Z"),
			"lastHeartbeatRecv" : ISODate("2018-01-30T02:39:57.220Z"),
			"pingMs" : NumberLong(0),
			"syncingTo" : "localhost:10001",
			"configVersion" : 1
		},
		{
			"_id" : 3,
			"name" : "localhost:10003",
			"health" : 0,
			"state" : 8,
			"stateStr" : "(not reachable/healthy)",
			"uptime" : 0,
			"optime" : {
				"ts" : Timestamp(0, 0),
				"t" : NumberLong(-1)
			},
			"optimeDurable" : {
				"ts" : Timestamp(0, 0),
				"t" : NumberLong(-1)
			},
			"optimeDate" : ISODate("1970-01-01T00:00:00Z"),
			"optimeDurableDate" : ISODate("1970-01-01T00:00:00Z"),
			"lastHeartbeat" : ISODate("2018-01-30T02:39:58.304Z"),
			"lastHeartbeatRecv" : ISODate("2018-01-30T02:39:21.208Z"),
			"pingMs" : NumberLong(0),
			"lastHeartbeatMessage" : "Connection refused",
			"configVersion" : -1
		}
	],
	"ok" : 1,
	"operationTime" : Timestamp(1517279996, 1),
	"$clusterTime" : {
		"clusterTime" : Timestamp(1517279996, 1),
		"signature" : {
			"hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
			"keyId" : NumberLong(0)
		}
	}
}
MongoDB Enterprise gabriel:PRIMARY>

Connect to the master node

mongo localhost:10001

shut down the master node

mongo localhost:10001

show all databases

MongoDB Enterprise gabriel:PRIMARY> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB
test    0.000GB

switch to admin

MongoDB Enterprise gabriel:PRIMARY> use admin
switched to db admin

To stop the database, you must enter the admin library

MongoDB Enterprise gabriel:PRIMARY> db.shutdownServer()

response

2018-01-30T02:51:34.503+0000 I NETWORK  [thread1] trying reconnect to localhost:10001 (127.0.0.1) failed
2018-01-30T02:51:35.398+0000 I NETWORK  [thread1] Socket recv() Connection reset by peer 127.0.0.1:10001
2018-01-30T02:51:35.398+0000 I NETWORK  [thread1] SocketException: remote: (NONE):0 error: SocketException socket exception [RECV_ERROR] server [127.0.0.1:10001] 
2018-01-30T02:51:35.399+0000 I NETWORK  [thread1] reconnect localhost:10001 (127.0.0.1) failed failed 
2018-01-30T02:51:35.404+0000 I NETWORK  [thread1] trying reconnect to localhost:10001 (127.0.0.1) failed
2018-01-30T02:51:35.404+0000 W NETWORK  [thread1] Failed to connect to 127.0.0.1:10001, in(checking socket for error after poll), reason: Connection refused
2018-01-30T02:51:35.404+0000 I NETWORK  [thread1] reconnect localhost:10001 (127.0.0.1) failed failed 
MongoDB Enterprise >

Check if it is really stopped, and find that there are no 10001 node processes anymore

root@souyunku-2:# ps -ef | grep mongo
root      5554     1  0 Jan29 ?        00:03:34 mongod --dbpath /data/db/node2 --port 10002 --replSet gabriel --nojournal --fork --logpath /data/db/node2.log
root     12284     1  0 02:43 ?        00:00:02 mongod --dbpath /data/db/node3 --port 10003 --replSet gabriel --nojournal --fork --logpath /data/db/node3.log
root     12436  5132  0 02:53 pts/1    00:00:00 grep --color=auto mongo
root@souyunku-2:# netstat -nltp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 127.0.0.1:10002         0.0.0.0:*               LISTEN      5554/mongod     
tcp        0      0 127.0.0.1:10003         0.0.0.0:*               LISTEN      12284/mongod          
root@souyunku-2:/data/db#

Check if the fault is professional

root@souyunku-2:# mongo localhost:10001

View master-slave status

MongoDB Enterprise gabriel:SECONDARY> rs.status()
{
	"set" : "gabriel",
	"date" : ISODate("2018-01-30T02:56:48.074Z"),
	"myState" : 2,
	"term" : NumberLong(2),
	"syncingTo" : "localhost:10003",
	"heartbeatIntervalMillis" : NumberLong(2000),
	"optimes" : {
		"lastCommittedOpTime" : {
			"ts" : Timestamp(1517280995, 1),
			"t" : NumberLong(2)
		},
		"readConcernMajorityOpTime" : {
			"ts" : Timestamp(1517280995, 1),
			"t" : NumberLong(2)
		},
		"appliedOpTime" : {
			"ts" : Timestamp(1517281005, 1),
			"t" : NumberLong(2)
		},
		"durableOpTime" : {
			"ts" : Timestamp(1517280995, 1),
			"t" : NumberLong(2)
		}
	},
	"members" : [
		{
			"_id" : 1,
			"name" : "localhost:10001",
			"health" : 0,
			"state" : 8,
			"stateStr" : "(not reachable/healthy)",
			"uptime" : 0,
			"optime" : {
				"ts" : Timestamp(0, 0),
				"t" : NumberLong(-1)
			},
			"optimeDurable" : {
				"ts" : Timestamp(0, 0),
				"t" : NumberLong(-1)
			},
			"optimeDate" : ISODate("1970-01-01T00:00:00Z"),
			"optimeDurableDate" : ISODate("1970-01-01T00:00:00Z"),
			"lastHeartbeat" : ISODate("2018-01-30T02:56:47.605Z"),
			"lastHeartbeatRecv" : ISODate("2018-01-30T02:51:34.519Z"),
			"pingMs" : NumberLong(0),
			"lastHeartbeatMessage" : "Connection refused",
			"configVersion" : -1
		},
		{
			"_id" : 2,
			"name" : "localhost:10002",
			"health" : 1,
			"state" : 2,
			"stateStr" : "SECONDARY",
			"uptime" : 59660,
			"optime" : {
				"ts" : Timestamp(1517281005, 1),
				"t" : NumberLong(2)
			},
			"optimeDate" : ISODate("2018-01-30T02:56:45Z"),
			"syncingTo" : "localhost:10003",
			"configVersion" : 1,
			"self" : true
		},
		{
			"_id" : 3,
			"name" : "localhost:10003",
			"health" : 1,
			"state" : 1,
			"stateStr" : "PRIMARY",
			"uptime" : 784,
			"optime" : {
				"ts" : Timestamp(1517281005, 1),
				"t" : NumberLong(2)
			},
			"optimeDurable" : {
				"ts" : Timestamp(1517281005, 1),
				"t" : NumberLong(2)
			},
			"optimeDate" : ISODate("2018-01-30T02:56:45Z"),
			"optimeDurableDate" : ISODate("2018-01-30T02:56:45Z"),
			"lastHeartbeat" : ISODate("2018-01-30T02:56:46.486Z"),
			"lastHeartbeatRecv" : ISODate("2018-01-30T02:56:47.147Z"),
			"pingMs" : NumberLong(0),
			"electionTime" : Timestamp(1517280703, 1),
			"electionDate" : ISODate("2018-01-30T02:51:43Z"),
			"configVersion" : 1
		}
	],
	"ok" : 1,
	"operationTime" : Timestamp(1517281005, 1),
	"$clusterTime" : {
		"clusterTime" : Timestamp(1517281005, 1),
		"signature" : {
			"hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
			"keyId" : NumberLong(0)
		}
	}
}
MongoDB Enterprise gabriel:SECONDARY> 

Found "name" : "localhost:10001", "stateStr" : "(not reachable/healthy)", the health status is already "unreachable"

The master node has been switched to the 10003 node

"_id" : 3,
"name" : "localhost:10003",
"health" : 1,
"state" : 1,
"stateStr" : "PRIMARY",

Restart node 10001

mongod --dbpath /data/db/node1 --port 10001 --replSet gabriel --nojournal --fork --logpath /data/db/node1.log

refer to:

Runoob Tutorial: http://www.runoob.com/mongodb/mongodb-tutorial.html
Tutorials Tutorial: Pointhttps://www.tutorialspoint.com/mongodb/mongodb_advantages.htm
MongoDB official website address: https://www.mongodb. com
MongoDB official English documentation: https://docs.mongodb.com/manual
MongoDB download address for each platform: https://www.mongodb.com/download-center#community
MongoDB installation https://docs.mongodb.com/ manual/tutorial/install-mongodb-enterprise-on-ubuntu

Contact

  • Author: Peng Lei
  • Source: http://www.ymq.io/2018/01/29/MongoDB-2
  • Email:[email protected]
  • The copyright belongs to the author, please indicate the source when reprinting
  • Wechat: Pay attention to the public account, search cloud library, focus on research and knowledge sharing of development technology

Follow the official account - Soyun Library

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325136576&siteId=291194637