Build MongoDB server, MongoDB Basic use, data import and export

Source: Internet
Author: User
Tags findone log log mkdir mongodb server mongodump mongorestore

Mongodb

1.1 Software Introduction

? A product between a relational database and a non-relational database

– a database based on distributed file storage.

– written in the C + + language. Designed to provide scalable, high-performance data storage solutions for WEB applications.

–mongodb stores data as a document and data structures are composed of key-value (key=>value) pairs.

The –mongodb document resembles a JSON object. Field values can contain other documents, arrays, and array of documents.

1.2 Software Features

– Easy Installation

– Easy and easy to work with for document storage

– Support for rich query representations

– You can set the index of any property

– Support for mainstream programming languages ruby| python| java| php| C++

– Support for replica sets, shards

Building a MongoDB server

2.1 Package

[Email protected] ~]# TAR-XF mongodb-linux-x86_64-rhel70-3.6.3.tgz

[[email protected] ~]# ls mongodb-linux-x86_64-rhel70-3.6.3

[Email protected] bin]# Mkdir/usr/local/mongodb

[Email protected] ~]# MV Mongodb-linux-x86_64-rhel70-3.6.3/bin/usr/local/mongodb/bin

[Email protected] ~]# Cd/usr/local/mongodb/bin

[[email protected] mongodb]# mkdir etc log #etc配置文件 log log file

[Email protected] mongodb]# mkdir-p data/db

2.2 Creating a configuration file

[[email protected] bin]#./mongod--help See Help

[Email protected] etc]# cd/usr/local/mongodb/etc/

[Email protected] etc]# vim mongodb.conf

Logpath=/usr/local/mongodb/log/mongodb.log

Logappend=true # Additional way to log information

DBPATH=/USR/LOCAL/MONGODB/DATA/DB # Database Directory

Fork=true # daemon Mode run

bind_ip=192.168.4.50

port=27050

2.3 Activating Service

[Email protected] mongodb]# ln-s/usr/local/mongodb/bin/*/sbin/

[Email protected] ~]# mongod-f/usr/local/mongodb/etc/mongodb.conf #開啓服務

[Email protected] mongodb]# Mongod--shutdown-f/usr/local/mongodb/etc/mongodb.conf #關閉服務

2.3.1 Viewing processes

[Email protected] log]# ps-c Mongod

PID TTY Time CMD

2432? 00:00:00 Mongod

2.3.2 Viewing ports

[Email protected] log]# Netstat-antulp | grep:27017

TCP 0 0 127.0.0.1:27017 0.0.0.0:* LISTEN 2432/mongod

2.3.3 See if there are any journal files

[[email protected] log]# ls

Mongodb.log

2.4 Connect Service

[Email protected] log]# MONGO

MongoDB Shell version v3.6.3

Connecting to:mongodb://127.0.0.1:27017

MongoDB Server version:3.6.3

..............

2018-07-07t10:49:21.013+0800 I CONTROL [initandlisten] * * We suggest setting it to ' never '

2018-07-07t10:49:21.013+0800 I CONTROL [Initandlisten]

Show DBS//Show existing libraries

Admin 0.000GB

Config 0.000GB

Local 0.000GB

DB//shown when the library

Test

Exit # Disconnect

Bye

MongoDB Basic Use

3.1 Specifying the service IP address

[Email protected] log]# killall-9 Mongod

[Email protected] mongodb]# vim etc/mongodb.conf

bind_ip=192.168.4.50 changing IP

port=27050 changing ports

~

[Email protected] mongodb]# mongod-f/usr/local/mongodb/etc/mongodb.conf

[Email protected] mongodb]# Netstat-antulp | grep:27050

TCP 0 0 192.168.4.50:27050 0.0.0.0:* LISTEN 2794/mongod

[Email protected] mongodb]# mongo-host 192.168.4.50-port 27050

3.2 Creating a name for easy-to-activate shutting down

[Email protected] ~]# VIM/ROOT/.BASHRC

Alias mstart= ' Mongod-f/usr/local/mongodb/etc/mongodb.conf '

Alias mstop= ' Mongod--shutdown-f/usr/local/mongodb/etc/mongodb.conf '

3.3 Common management commands

–show DBS View Existing libraries

–DB Displays the current library

–use Library name Switch Library, if the library does not exist automatically delay the creation of the library

–show collections or Show tables view the existing collections under the library

–db.dropdatabase () Delete the currently located library

3.4 Database naming rules

The database name can be any UTF-8 string that meets the following criteria.

– Cannot be an empty string ("").

– Must not contain ' (spaces),. , $,/, \, and (null characters)

– should be all lowercase.

– Up to 64 bytes.

3.5 Collection Management Commands: View create delete

–show collections or Show tables # View Collection

–db. Collection name. Drop () #刪除集合

–db. The collection name, save ({', '}) # # Creates a collection that does not exist

#在时, create and add a document

Db.user.save ({' name ': ' Bob ', ' Age ': ' 21 '})

Writeresult ({"ninserted": 1})

Use Studb

Switched to DB Studb

Db

Studb

Show tables

Db.c1.save ({name: "Bob", Age:19,sex: "Boy"})

Writeresult ({"ninserted": 1})

Db.c1.save ({name: "Harry", Age:20,sex: "Girl"})

Writeresult ({"ninserted": 1})

Db.c1.find

Show tables

C1

Basic document Management

Documentation: Records similar to the MySQL table

4.1 Basic Document Management

Document management Commands: View statistics Add Delete

–db. Collection name. Find ()

 > db.c1.find()

–db. Collection name. Count ()

 > db.c1.count() 2

–db. Collection name. Insert ({"Name": "Jim"})

 > db.c1.insert({"name":"jim","age":11,"sex":"boy"}) WriteResult({ "nInserted" : 1 })

–db. Collection name. Find ({condition})

 > db.c1.find({"age":11})  { "_id" : ObjectId("5b405853f250badccca5adb8"), "name" : "jim", "age" : 11, "sex" :   "boy" }

–db. The collection name. FindOne () # Returns a document

  > db.c1.findOne(){"_id" : ObjectId("5b403a1af250badccca5adb6"),"name" : "bob","age" : 19,"sex" : "boy"

}

–db. Collection name. Remove ({}) # Delete all documents

> db.c1.remove({})

–db. Collection name. Remove ({condition}) # Delete all documents that match the criteria

Db.c1.remove ({"Name": "Bob"})

Writeresult ({"nremoved": 1})

Basic data types

5.1 characters string/Boolean bool/null

Strings string

–utf-8 strings can be represented as string types of data

–{name: "Zhang San"} or {school: "Tarena"}

? boolean bool

– Boolean type has two values of true and False, {x:true}

Db.c1.save ({name: "Tom", Age:19,sigle:true})

? Empty null

– for fields that represent null values or nonexistent, {x:null}

Db.c1.save ({name: "Lucy", Age:18,sigle:false,pay:null})

5.2 Values/Arrays array

5.2.1 Value

–shell uses 64 as a floating-point value by default. {x:3.14} or {x:3}.

> db.c1.save({name:"yaya",x:3.99})

–numberint (4-byte integer) {x:numberint (3)}

Db.c1.save ({"Name": "Zhangsan", X:numberint (3)})

–numberlong (8-byte integer) {X:numberlong (3)}

Db.c1.save ({name: "Yaya", X:numberlong (3)})

Db.c1.find ()

{"_id": ObjectId ("5b403a4bf250badccca5adb7"), "name": "Harry", "age": +, "Sex": "Girl"}

{"_id": ObjectId ("5B405853F250BADCCCA5ADB8"), "name": "Jim", "Age": One, "Sex": "Boy"}

{"_id": ObjectId ("5B405E31F250BADCCCA5ADB9"), "name": "Zhangsan", "X": 3}

{"_id": ObjectId ("5b405ec1f250badccca5adba"), "name": "Tom", "Age": +, "Sigle": true}

{"_id": ObjectId ("5B405F36F250BADCCCA5ADBB"), "name": "Lucy", "Age": +, "Sigle": false, "pay": null}

{"_id": ObjectId ("5b405f9bf250badccca5adbc"), "name": "Yaya", "X": 3.99}

{"_id": ObjectId ("5b405fdef250badccca5adbd"), "name": "Yaya", "X": Numberlong (3)}

5.2.2 Arrays Array

– A data list or dataset can represent an array

–{x: ["A", "B", "C"]}

5.3 Code/Date/Object

Code

– Any JavaScript code can be included in queries and documents

–{x:function () {/ code /}}

? Date

– The date is stored as the number of milliseconds elapsed since the new era, no time zone is stored

–{x:new Date ()}

Db.c1.save ({name: "Liwei", Birthday:new Date ()})

? Object

– The object ID is a 12-byte string, which is the unique identifier of the document

–{x:objectid ()}

Db.c1.save ({name: "Xiaodong", Stuid:objectid ()})

5.4 Inline/Regular expressions

5.4.1 Inline

– Documents can be nested in other documents, processed as values by nested documents

–{tarena: {address: "Beijing", Tel: "888888", Perso

N: "Hanshaoyun"

– }}

Db.c1.save ({

... ywzd:{p: "Dmy", Jg:69,v:2},

... ngsfc:{p: "Birdg", Jg:89,v:4}

... })

5.4.2 Regular Expressions

– When querying, use regular expressions as a qualifying condition

–{x:/ Regular Expression/}

Db.c1.save ({

... name: "Hanmm", match:/^a/

... })

Data Import Export

6.1 Data export

Syntax Format 1

Mongoexport [--host IP address--port Port]

D Library name-C set name-F field Name 1, field name 2

--type=csv > Directory name/file name. csv

[Email protected] mnt]# mongoexport--host 192.168.4.50--port 27050-d studb-c c1-f _id,name--type=csv >/mnt/c1.c Sv

2018-07-07t16:31:22.526+0800 Connected to:192.168.4.50:27050

2018-07-07t16:31:22.527+0800 exported 7 Records

? Syntax Format 2

– #mongoexport--host IP address--port Port

    • Library name-C set name-Q ' {condition} '-F field name 1, field name 2

--type=csv > Directory name/file name. csv

* Note: The export to CSV format must use the-F to specify a list of field names!!!

Syntax Format 3

Mongoexport [--host IP address--port Port]

-D Library name-C collection name [-Q ' {condition} ' –f field List

]

--type=json

Directory name/file name. JSON

[Email protected] mnt]# mongoexport--host 192.168.4.50--port 27050-d studb-c C1--type=json >/mnt/c1.json

2018-07-07t15:50:46.202+0800 Connected to:192.168.4.50:27050

2018-07-07t15:50:46.203+0800 exported 7 Records

6.2 Data Import

Syntax Format 1

– #mongoimport –host IP address –port Port

-d Library name –c collection name

--type=json

Directory name/file name. JSON

[Email protected] mnt]# mongoimport--host 192.168.4.50--port 27050-d bbsdb-c T1--type=json/mnt/c1.json

2018-07-07t16:20:39.777+0800 Connected to:192.168.4.50:27050

2018-07-07t16:20:40.115+0800 Imported 7 Documents

[Email protected] mnt]# mongoimport--host 192.168.4.50--port 27050-d bbsdb-c t2-f _id,name--type=csv/mnt/c1.csv

2018-07-07t16:43:37.797+0800 Connected to:192.168.4.50:27050

2018-07-07t16:43:37.953+0800 Imported 8 Documents

Syntax Format 2

– #mongoimport –host IP address –port Port

-d Library name –c collection name

--type=csv--headerline [--drop] Directory name/file name. csv

Note: When the libraries and collections do not exist when the data is imported, the libraries and collections are created, the data is imported, and the data is imported into the collection by appending, using the-drop option to delete the existing data and import the new data--headerline ignore the title

[Email protected] mnt]# mongoimport--host 192.168.4.50--port 27050-d studb-c C1--headerline--drop--type=csv/mnt/c 1.csv

2018-07-07t17:00:41.677+0800 Connected to:192.168.4.50:27050

2018-07-07t17:00:41.678+0800 DROPPING:STUDB.C1

2018-07-07t17:00:41.967+0800 Imported 7 Documents

Bring the system user information into MongoDB

Create a new file

Db.c3.save ({name: "Yaya", Pass: "X", UID: "123", GID: "123", Comment: "Teacher", Homeaddr: "/home/bin", Shell: "/bin/bash"} )

And then the

[Email protected] mnt]# mongoexport--host 192.168.4.50--port 27050-d bbsdb-c c3-f name,pass,uid,gid,comment,homeaddr , Shell--type=csv >/mnt/c3.csv

2018-07-07t17:34:29.526+0800 Connected to:192.168.4.50:27050

2018-07-07t17:34:29.527+0800 exported 1 record

[Email protected] mnt]# cp/etc/passwd.

[[email protected] mnt]# ls

C1.csv C1.json c3.csv passwd

[Email protected] mnt]# sed-i ' c3.csv

[Email protected] mnt]# sed-i ' $r passwd ' c3.csv

[Email protected] mnt]# vim C3.csv

[Email protected] mnt]# sed-i ' s/:/,/g ' c3.csv

[Email protected] mnt]# vim C3.csv

C3.csv D into the repository

[Email protected] mnt]# mongoimport--host 192.168.4.50--port 27050 \

-D studb-c C3--headerline--drop--type=csv/mnt/c3.csv

2018-07-07t17:45:47.963+0800 Connected to:192.168.4.50:27050

2018-07-07t17:45:47.964+0800 dropping:studb.c3

2018-07-07t17:45:48.121+0800 Imported Documents

[Email protected] ~]# mongo-host 192.168.4.50-port 27050 #登錄數據庫查看

Db.c3.find ()

{"_id": ObjectId ("5b408bcb7f8c3df38b1fca2d"), "name": "Yaya", "Pass": "X", "UID": 123, "GID": 123, "comment": "Teac Her "," homeaddr ":"/home/bin "," Shell ":"/bin/bash "}

{"_id": ObjectId ("5b408bcb7f8c3df38b1fca2e"), "name": "Root", "Pass": "X", "UID": 0, "GID": 0, "comment": "Root", " Homeaddr ":"/root "," Shell ":"/bin/bash "}

{"_id": ObjectId ("5b408bcb7f8c3df38b1fca2f"), "name": "Bin", "Pass": "X", "UID": 1, "GID": 1, "comment": "Bin", "ho Meaddr ":"/bin "," Shell ":"/sbin/nologin "}

{"_id": ObjectId ("5b408bcb7f8c3df38b1fca30"), "name": "Daemon", "Pass": "X", "UID": 2, "GID": 2, "comment": "Daemon "," homeaddr ":"/sbin "," Shell ":"/sbin/nologin "}

............................

Data Backup Recovery

7.1 Data Backup

Back up data all libraries into the current directory under the Dump directory

[Email protected] mnt]# mongodump--host 192.168.4.50--port 27050-d bbsdb

2018-07-07t17:56:11.403+0800 writing Bbsdb.t2 to

2018-07-07t17:56:11.403+0800 writing Bbsdb.t1 to

2018-07-07t17:56:11.403+0800 writing bbsdb.c3 to

2018-07-07t17:56:11.405+0800 Done Dumping BBSDB.T2 (8 documents)

# mongodump [--host IP address--port port

Specify the backup library and backup directory when backing up

# mongodump [--host IP address--port port]-d database name

-C collection Name-O directory (the directory is specified when the backup is not created beforehand!!! )

? View Bson File contents

#bsondump./dump/bbs/t1.bson

7.2 Data Recovery

Syntax format

–mongorestore--host IP Address--port Port-D number

Backup directory name according to library name [-C collection name]

[Email protected] mnt]# mongorestore--host 192.168.4.50--port 27050-d db1-c T1/mnt/mogobak/bbsdb/t2.bson

2018-07-07t18:04:47.914+0800 checking for collection data In/mnt/mogobak/bbsdb/t2.bson

2018-07-07t18:04:47.914+0800 reading metadata for DB1.T1 From/mnt/mogobak/bbsdb/t2.metadata.json

Build MongoDB server, MongoDB Basic use, data import and export

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.