Mongo introduction

An overview of the

download

MongoDB provides pre-compiled binaries for both 32-bit and 64-bit systems, which you can download and install from the MongoDB website. Official address: www.mongodb.com/

This tutorial download version 3.4: downloads.mongodb.org/win32/mongo…

Mongo installation

Install mongodb in Windows 7 system requires vc++ runtime, if not, the message “cannot start this program because vcruntime140.dll is missing on the computer.”

Setting the configuration file

Create several folders as follows: database path (data directory), log path (logs directory) and log file (mongo.log file)

Create the configuration file mongo.conf with the following contents:

The mongo.conf configuration file contains the following classes:

# database path
dbpath=F:\study_app\MongoDB\mongodbWorkspace\data
# log path
logpath=F:\study_app\MongoDB\mongodbWorkspace\logs\mongo.log
# set authentication
auth=true
Copy the code

Installing the MongoDB Service

Use the –install option to install the service by executing bin/ god. Exe, and use the –config option to specify the configuration file you created earlier. CMD: F: study_app: MongoDB: mongodbWorkspace: bin

Register Mongodb with the service

Mongod. Exe ‐ ‐ config"F:\study_app\MongoDB\mongodbWorkspace\mongo.conf"‐ ‐ installCopy the code

Start the service

net start MongoDB
Copy the code

Disabling the MongoDB service

net stop MongoDB
Copy the code

Removing the MongoDB Service

"F:\study_app\MongoDB\mongodbWorkspace\bin\mongod.exe"‐ ‐ removeCopy the code

Start the mongodb service. After the command is executed, enter http://127.0.0.1:27017 in the address box of the browser. If the following page is displayed, the mongodb service is successfully started

You can also use mongo.exe in the bin directory to connect to mongodb

Install studio3t

  • Is a visual interface for Mongodb (similar to Sqlyog)
  • Studio3t is an excellent client tool for mongodb. The official address is https://studio3t.com/

Download studio3t

Install and start:

Fill in connection information:

Connection successful:

Introduction to mongo

Basic concept

  • In mongodb, data is managed by database, collection and document. The following is a comparison of some concepts between mongodb and relational database:

  • A single mongodb instance can create multiple databases
  • A database can create multiple collections
  • A collection can contain multiple documents

Connect the mongo

  • Mongodb is used in client-server mode, that is, a client is used to connect to the mongodb database (server).
The command format
mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?
options]]
Copy the code
  • Mongodb :// Fix the prefix
  • Username: indicates the account
  • Password: specifies the password
  • Host: specifies the host name or IP address. This parameter is mandatory only for host.
  • Port: indicates the port number. The default value is 27017
  • /database: Connects to a database
  • ? Options: connection parameters, key/value pair
Example:
Mongodb ://localhost Connect to port 27017 of the local database mongodb://root:itcast@localhost Connect to port 27017 of the local database using the username root and the password itcast Mongo: / / localhost, localhost: 27018, localhost: 27019, connecting the three master slave server, port 27017, 27018, 27019Copy the code
Use mongodb’s javascript shell (mongo.exe) to connect
  • The Mongo. exe client program is found in the bin directory in the installation directory

Connect using a Java program

Github. IO /mongo-java-…

  • Add dependencies:
< the dependency > < groupId > org. Mongo < / groupId > < artifactId > mongo Java ‐ ‐ driver < / artifactId > < version > rule 3.4.3 < / version > </dependency>Copy the code
  • Test procedure:
@Test
public void testConnectionMongoClient = new MongoClient(){MongoClient = new MongoClient()"localhost", 27017); //MongoClientURI connectionString = new MongoClientURI("mongodb://root:root@localhost:27017"); //MongoClient mongoClient = new MongoClient(connectionString); MongoDatabase database = mongoclient.getdatabase ("test"); // MongoCollection<Document> collection = database.getCollection("student"); Document myDoc = collection.find().first(); // Get the file content json String String json = mydoc.tojson (); System.out.println(json); }Copy the code

The database

Querying the database

Show DBS Queries all databases

Db Displays the current database

Command format:
use DATABASE_NAME
Copy the code
Example:

use test02

If the test02 database exists, switch to the database; if the test02 database does not exist, create the database.

Note:

The newly created database is not displayed and needs to include at least one collection.

Delete database (use with caution!!)
  • Command format:
db.dropDatabase()
Copy the code
Example:

Delete the test02 database

Switch the database first: use test02

Db.dropdatabase ()

A collection of

  • Collections are equivalent to tables in a relational database. A database can create multiple collections. A collection manages documents of the same type
1. Create a collection
Db.createcollection (name, options) Name: name of the newly created collection options: creation parametersCopy the code
2. Delete the collection
Db.collection.drop () example: db.student.drop() drops the student collectionCopy the code

The document

Inserted into the document
  • The document format in mongodb is JSON. The following is a document containing two keys: _id primary key and name
{
"_id" : ObjectId("5b2cc4bfa6a44812707739b5"),
"name" : "jetty"
}

Copy the code
  • Insert command:
db.COLLECTION_NAME.insert(document)
Copy the code
  • By default, each document uses _ID as the primary key. The default primary key type is ObjectId (object type). Mongodb automatically generates the primary key value. Example:
db.student.insert({"name":"jetty"."age"10}) :Copy the code
Update the document
  • Command format:
Db.collection. update(<query>, <update>, <options>) query: a query condition equivalent to an SQL statementwhereUpdate: Updates the document content. Options: indicates optionsCopy the code
Delete the document
  • Command format:
Db.student. Remove (<query>) query: delete condition, equivalent to SQL statementwhere
Copy the code
Query the document
  • Command format:
Db.collection. find(query, projection) query: specifies the query criteria for projectionCopy the code
  • All the query
db.student.find()
Copy the code
The user
Create a user
  • Syntax format:
mongo>db.createUser(
{ user: "<name>".pwd: "<cleartext password>",
customData: { <any information> },
roles: [
{ role: "<role>", db: "<database>" } | "<role>". ] })Copy the code
  • Example:
  • Example Create user root as user root
use admin
db.createUser(
{
user:"root".pwd:"root",
roles:[{role:"root",db:"admin"}]})Copy the code
The built-in roles are as follows:
  • Database user roles: read and readWrite.
  • Database management roles: dbAdmin, dbOwner, and userAdmin.
  • Cluster management roles: clusterAdmin, clusterManager, clusterMonitor, and hostManager.
  • Backup and restoration roles: Backup and restore.
  • All database roles: readAnyDatabase, readWriteAnyDatabase, userAdminAnyDatabase, and dbAdminAnyDatabase
  • Super user role: root
Query the user
  • Query all users under the current library:
show users
Copy the code
Delete user
  • Syntax format:
db.dropUser("Username")
Copy the code
  • Example:
  • Example Delete a root1 user
db.dropUser("root1")
Copy the code
Modify the user
  • Syntax format:
db.updateUser(
"<username>",
{
customData : { <any information> },
roles : [
{ role: "<role>", db: "<database>" } | "<role>". ] .pwd: "<cleartext password>"
},
writeConcern: { <write concern> })
Copy the code
  • Example: Change the role of user root to readWriteAnyDatabase
use admin
db.updateUser("root",{roles:[{role:"readWriteAnyDatabase",db:"admin"}]})
Copy the code
Change the password
db.changeUserPassword("username"."newPasswd")
Copy the code
  • Syntax format:
db.changeUserPassword("username"."newPasswd")
Copy the code
  • For example, change the password of user root to 123
use admin
db.changeUserPassword("root"."123")
Copy the code