In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >
Share
Shulou(Shulou.com)06/01 Report--
A brief introduction to Mongodb the official website address: http://www.mongodb.org/
MongoDB is a high-performance, open source, schemalless document database, which is one of the most popular NoSql databases. MongoDB is a product between relational database and non-relational database, which is a function of non-relational database.
The richest, most like a relational database. It can be used to replace the traditional relational database or key / value storage in many scenarios. It is an open source database system based on distributed file storage written by C++ language. Its purpose is to provide information for WEB.
Use to provide scalable, high-performance data storage solutions. MongoDB is a product between relational database and non-relational database, which is the most functional and most like relational database among non-relational databases. The data structures it supports
Very loose, the data will be stored as a document, the data structure consists of key-value pairs (key= > value), is similar to json bson format, field values can contain other documents, arrays and document arrays, so you can store more complex data types.
II. Characteristics of Mongodb
MongoDB is characterized by high performance, easy to deploy and easy to use, and it is very convenient to store data. the biggest feature is that the query language it supports is very powerful, its syntax is somewhat similar to the object-oriented query language, and it can almost realize a single table similar to a relational database.
Most of the functions of queries, but also support indexing of data. The main features of MongoDB are summarized as follows:
1) provides a set-oriented document storage, easy to store data of object types, and a non-relational database that is simple and easy to operate.
2) use the update () command to replace the completed document (data) or some specified data fields.
3) dynamic query is supported.
4) full indexing is supported, including internal objects, and the index of any property can be set in the MongoDB record to achieve faster sorting.
5) replication and failure recovery are supported.
6) use efficient binary data storage, including large objects such as video, etc.
7) GridFS is a built-in feature in MongoDB that can be used to store a large number of small files.
8) automatically process fragments to support scalability at the cloud computing level; if the load increases (requiring more storage space and stronger processing power), it can be distributed among other nodes in the computer network, which is called fragmentation.
9) support multiple languages such as RUBY,PYTHON,JAVA,C++,PHP,C#.
10) the file is stored in BSON (an extension of JSON), MongoDB supports rich query expressions, and query instructions use tags in the form of JSON to easily query objects and arrays embedded in documents.
11) MongoDB allows scripts to be executed on the server. You can write a function in JavaScript and execute it directly on the server, or store the definition of the function on the server and call it directly next time.
12) it can be accessed through the network, and data mirrors can be created locally or over the network, which makes MongoDB more scalable.
Inadequacies of Mongodb
1) the data is unevenly distributed in the cluster fragmentation.
2) the reliability of single machine is poor.
3) A large amount of data is continuously inserted, and the write performance fluctuates greatly.
4) transaction operations are not supported. So a system that requires strict transactions (if the banking system) certainly can't use it.
5) it takes up a lot of disk space. The reasons for the large footprint are as follows:
1-> pre-allocation of space: to avoid forming too many hard disk fragments, mongodb applies to generate a large chunk of hard disk space every time there is insufficient space, and the amount of applications increases exponentially from 64m, 128m, 256m until 2G is a single file.
The maximum volume of. As the amount of data increases, you can see these whole blocks of files with increasing capacity in their data directory.
2-> space occupied by field names: in order to keep the structural information in each record for query, mongodb needs to store the key-value of each field in the form of BSON, if the value domain is small relative to the key domain, for example
If you store numeric data, the overhead of the data is the largest. One way to reduce space footprint is to keep the field name as short as possible so that it takes up less space, but this requires a tradeoff between readability and space footprint.
3-> Delete records do not release space: it is easy to understand that in order to avoid large-scale movement of the deleted data, the original record space is not deleted, only marked "deleted", and can be reused in the future.
4-> you can run db.repairDatabase () periodically to organize records, but the process will be slow.
III. Mongodb function
1) Collection-oriented storage: suitable for storing objects and data in JSON form.
2) dynamic query: Mongo supports rich query expressions. Query instructions use tags in the form of JSON to easily query objects and arrays embedded in a document.
3) complete indexing support: including document embedded objects and arrays. Mongo's query optimizer parses the query expression and generates an efficient query plan.
4) query monitoring: Mongo includes a monitoring tool for analyzing the performance of database operations.
5) replication and automatic failover: Mongo database supports data replication between servers, master-slave mode and mutual replication between servers. The primary goal of replication is to provide redundancy and automatic failover.
6) efficient traditional storage: support for binary data and large objects (such as photos or pictures)
7) automatic sharding to support cloud-level scalability: the automatic sharding feature supports horizontal database clusters and can dynamically add additional machines.
4. Mongodb usage scenarios
Applicable scenarios:
Real-time data processing of the website. It is very suitable for real-time insertion, update and query, and has the replication and high scalability required for website real-time data storage; cache, because of its high performance, it is suitable to be used as the cache layer of information infrastructure. After the system restarts
The persistence cache layer built by it can avoid the overload of data sources in the lower layer. A highly scalable scene. Ideal for a database of dozens or hundreds of servers, its roadmap already includes built-in support for the MapReduce engine.
Does not apply to scenarios:
Highly transactional systems are required. Traditional business intelligence applications. Complex cascading queries across documents (tables).
5. Install Mongodb using the official website download address: http://www.mongodb.org/downloads
1) install mongodb
[root@data-server src] # cd / usr/local/src/
[root@data-server src] # tar-zvxf mongodb-linux-x86_64-rhel62-3.4.4
[root@data-server src] # mv mongodb-linux-x86_64-rhel62-3.4.4 / usr/local/mongodb
[root@data-server src] # cd / usr/local/mongodb / / Mongodb home directory
[root@data-server mongodb] # ll
Total dosage 120
Drwxr-xr-x. 2 root root 4096 June 3 14:51 bin
-rw-r--r--. 1 root root 34520 April 21 06:19 GNU-AGPL-3.0
-rw-r--r--. 1 root root 16726 April 21 06:19 MPL-2
-rw-r--r--. 1 root root 1359 April 21 06:19 README
-rw-r--r--. 1 root root 55625 April 21 06:19 THIRD-PARTY-NOTICES
[root@data-server mongodb] # mkdir / usr/local/mongodb/data / / Mongodb data directory, which can be stored in a separate large partition
[root@data-server mongodb] # mkdir / usr/local/mongodb/log / / Mongodb log directory
2) start Mongodb
Use the mongod command to establish a mongodb database link with port number set to 10001, database path to / usr/local/mongodb/data, and log path to / usr/local/mongodb/log/mogodb.log
The startup program of mongodb is executed in the background. After the following command is executed, press ctrl+c
[root@data-server mongodb] # nohup / usr/local/mongodb/bin/mongod-- dbpath=/usr/local/mongodb/data/-- logpath=/usr/local/mongodb/log/mongo.log &
The default port for mongodb is 27017
[root@data-server mongodb] # ps-ef | grep mongodb
Root 14858 14518 1 15:01 pts/1 00:00:01 / usr/local/mongodb/bin/mongod-dbpath=/usr/local/mongodb/data/-logpath=/usr/local/mongodb/log/mongo.log
Root 14887 14518 0 15:02 pts/1 00:00:00 grep mongodb
[root@data-server bin] # netstat-tunlp | grep 14858
Tcp 0 0 0.0.0.0:27017 0.0.0.0: LISTEN 14858/mongod
[root@data-server mongodb] # lsof-iRose 27017
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
Mongod 14858 root 7u IPv4 145311 0t0 TCP: 27017 (LISTEN)
3) set the environment variable of mongodb
[root@data-server ~] # vim / etc/profile
.
Export PATH=$PATH:/usr/local/mongodb/bin/
[root@data-server ~] # source / etc/profile
4) in order to start and close MongoDB more conveniently, we can write scripts using Shell, or of course, we can add it to service.
A better way is to use a configuration file, write the parameters required by MongoDB to the configuration file, and then reference it in the script
[root@data-server ~] # cat / usr/local/mongodb/mongodb.conf
# represents the port number. If not specified, it defaults to 27017.
Port=27017
# MongoDB data file directory
Dbpath=/usr/local/mongodb/data
# MongoDB log file directory
Logpath=/usr/local/mongodb/log/mongo.log
# automatic accumulation of log files
Logappend=true
Write a startup script
[root@data-server ~] # vim / etc/init.d/mongodb
#! / bin/bash
# mongod Start up the MongoDB server daemon
# source function library
. / etc/rc.d/init.d/functions
# define command
CMD=/usr/local/mongodb/bin/mongod
# define the configuration file path
INITFILE=/usr/local/mongodb/mongodb.conf
Start ()
{
# & indicates background startup, or you can use the fork parameter
$CMD-f $INITFILE &
Echo "MongoDB is running background..."
}
Stop ()
{
Pkill mongod
Echo "MongoDB is stopped."
}
Case "$1" in
Start)
Start
Stop)
Stop
)
Echo $"Usage: $0 {start | stop}"
Esac
[root@data-server ~] # chmod 755 / etc/init.d/mongodb
[root@data-server ~] # / etc/init.d/mongodb status
Usage: / etc/init.d/mongodb {start | stop}
[root@data-server ~] # / etc/init.d/mongodb stop
Terminated
[root@data-server] # lsof-iRose 27017
[root@data-server ~] # / etc/init.d/mongodb start
MongoDB is running background...
[root@data-server] # lsof-iRose 27017
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
Mongod 15138 root 7u IPv4 147713 0t0 TCP: 27017 (LISTEN)
Connect the MongoDB service through shell: (connect the native mongodb:mongo 182.48.115.238 mongodb:mongo 27017 on the client)
[root@data-server ~] # mongo
MongoDB shell version v3.4.4
Connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.4
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
Http://docs.mongodb.org/
Questions? Try the support group
Http://groups.google.com/group/mongodb-user
Server has startup warnings:
2017-06-03T15:17:54.695+0800 I STORAGE [initandlisten]
2017-06-03T15:17:54.695+0800 I STORAGE [initandlisten] WARNING: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine
2017-06-03T15:17:54.695+0800 I STORAGE [initandlisten] See http://dochub.mongodb.org/core/prodnotes-filesystem
2017-06-03T15:17:55.699+0800 I CONTROL [initandlisten]
2017-06-03T15:17:55.700+0800 I CONTROL [initandlisten] WARNING: Access control is not enabled for the database.
2017-06-03T15:17:55.700+0800 I CONTROL [initandlisten] Read and write access to data and configuration is unrestricted.
2017-06-03T15:17:55.700+0800 I CONTROL [initandlisten] WARNING: You are running this process as the root user, which is not recommended.
2017-06-03T15:17:55.700+0800 I CONTROL [initandlisten]
2017-06-03T15:17:55.700+0800 I CONTROL [initandlisten]
2017-06-03T15:17:55.700+0800 I CONTROL [initandlisten] WARNING: / sys/kernel/mm/transparent_hugepage/enabled is' always'.
2017-06-03T15:17:55.700+0800 I CONTROL [initandlisten] We suggest setting it to 'never'
2017-06-03T15:17:55.700+0800 I CONTROL [initandlisten]
2017-06-03T15:17:55.700+0800 I CONTROL [initandlisten] WARNING: / sys/kernel/mm/transparent_hugepage/defrag is' always'.
2017-06-03T15:17:55.700+0800 I CONTROL [initandlisten] * * We suggest setting it to 'never'
2017-06-03T15:17:55.700+0800 I CONTROL [initandlisten]
Help
Db.help () help on db methods
Db.mycoll.help () help on collection methods
Sh.help () sharding helpers
Rs.help () replica set helpers
Help admin administrative help
Help connect connecting to a db help
Help keys key shortcuts
Help misc misc things to know
Help mr mapreduce
Show dbs show database names
Show collections show collections in current database
Show users show users in current database
Show profile show most recent system.profile entries with time > = 1ms
Show logs show the accessible logger names
Show log [name] prints out the last segment of log in memory, 'global' is default
Use set current database
Db.foo.find () list objects in collection foo
Db.foo.find ({a: 1}) list objects in foo where a = = 1
It result of the last line evaluated; use to further iterate
DBQuery.shellBatchSize = x set default number of items to display on shell
Exit quit the mongo shell
-abnormal shutdown of mongodb leads to startup failure-
Mongodb was forcibly closed before, but when it was started again later, an error was found:
[root@i-omxpbsuo] # / usr/local/mongodb/bin/mongod-logpath / usr/local/mongodb/log/system.log-logappend-- dbpath / data/mongodb-- directoryperdb-- auth-- journal-- profile=1-- slowms=5-- fork
Forked process: 4853
All output going to: / usr/local/mongodb/log/system.log
View the log
This is due to the last abnormal shutdown of mongodb.
Solution:
1) delete the mongod.lock under the data directory / data/mongodb
[root@i-omxpbsuo ~] # rm-rf / data/mongodb/mongod.lock
2) repair mongodb
[root@i-omxpbsuo] # / usr/local/mongodb/bin/mongod-logpath-dbpath / data/mongodb-repair
3) Delete the j.room4 file under / data/mongodb/journal (or empty the file under journal)
[root@i-omxpbsuo ~] # rm-rf / data/mongodb/journal/*j._4
4) then start mongodb again and ok
[root@i-omxpbsuo] # / usr/local/mongodb/bin/mongod-- logpath-- dbpath / data/mongodb-- directoryperdb-- auth-- journal-- profile=1-- slowms=5-- fork &
The correct way to shut down mongod: enter mongo shell
Use admin
Db.shutdownServer ()
You can also kill it roughly according to the document, and there should be an KILL signal processor inside it.
Killall mongod please do not kill-9, will cause file data confusion and loss of repair is powerless.
You can also install mongodb as yum. The operation records are as follows:
1) create a repo
[root@data-server ~] # vim / etc/yum.repos.d/mongodb-org-3.2.repo
[mongodb-org-3.2]
Name=MongoDB Repository
Baseurl= https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/3.2/x86_64/
Gpgcheck=0
Enabled=1
2) install MongoDB and related tools
[root@data-server ~] # yum install-y mongodb-org
3) start Mongodb
[root@data-server ~] # service mongod start
Starting mongod: [OK]
[root@data-server ~] # chkconfig mongod on
[root@data-server] # lsof-iRose 27017
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
Mongod 26130 mongod 6u IPv4 2773161 0t0 TCP localhost:27017 (LISTEN)
Log file: / var/log/mongodb/mongod.log
Configuration file: / etc/mongod.conf
Data directory: / var/lib/mongo/
The configuration file explains:
[root@data-server ~] # cat / etc/mongod.conf
Mongo.conf
# where to log
Logpath=/var/log/mongo/mongod.log
Logappend=true # writes to the log as an append
Fork and run in background
Fork = true
# port = 27017 # Port
Dbpath=/var/lib/mongo # location for saving database files
Directoryperdb=true
Enables periodic logging of CPU utilization and I/O wait
# enable periodic recording of CPU utilization and IGM O wait
# cpu = true
Turn on/off security. Whether Off is currently the default runs in a secure authentication mode. The default is unauthenticated, non-secure mode.
# noauth = true
# auth = true
Verbose logging output. Detailed record output
# verbose = true
Inspect all client data for validity on receipt (useful fordeveloping drivers) is used to check the validity of data received by the client when developing a driver.
# objcheck = true
Enable db quota management enables database quota management. By default, each db can have 8 files, which can be set with the quotaFiles parameter.
# quota = true
Set oplog record level Set oplogging level where n is0=off (default) 1=W2=R3=both7=W+some reads
# oplog = 0
Diagnostic/debugging option dynamic debug item
# nocursors = true
Ignore query hints ignores query hints
# nohints = true
Disable the http interface, default to localhost:28017Disable the HTTP interface (Defaults to localhost:27018). This port number is wrong.
# nohttpinterface = true
Close the server-side script, which will greatly limit the function of Turns off server-side scripting. This will result in greatly limitedfunctionality
# noscripting = true
Turn off the scan table and any query will be a scan failure Turns off table scans. Any query that would do a table scan fails.
# notablescan = true
Close the data file pre-allocation Disable data file preallocation.
# noprealloc = true
Specifies the size of the. ns file for the new database, in MBSpecify. Ns file size for new databases.nssize = Accout token for Mongo monitoring server.
# mms-token =
The name of the mongo monitoring server Server name for Mongo monitoring server.
# mms-name =
The ping interval Ping interval for Mongo monitoring server of the mongo monitoring server.
# mms-interval =
Replication Options replication option in replicated mongo databases, specify here whether this is a slave or master in replication, specifies the current dependency
# slave = true
# source = master.example.com
Slave only: specify a single database to replicate
# only = master.example.com
Or
# master = true
# source = slave.example.com
VI. Daily operating orders of Mongodb
1) login and exit..
The mongo command directly adds the IP address of the MongoDB server to log in to Mongo using Mongo's default port number (27017), and then you can do simple command-line operations. As for quitting, just exit and enter.
If the default ip bound by bind is 127.0.0.1 and the port is 27017, you can log in using either of the following:
[root@master-node ~] # mongo
[root@master-node ~] # mongo 127.0.0.1purl 27017
If you bind a fixed ip address, such as bing_ip=182.48.115.236, the connection mongodb command is:
[root@master-node] # mongo 182.48.115.238purl 27017
If you are connecting to a library, the command is
[root@master-node ~] # mongo ip:port/ Library name-u user name-p password
Help
After logging in to the mongodb database, you can directly execute the help command to help view
Show collections
As you can see from the above, mongo will automatically connect to a database called test after logging in. If the database does not exist, mongo automatically sets up a database called test. In the above example, because there is no db named test on the Mongo server, mongo creates a new empty db named test. There is no collection.
2) database level operation..
2.1 View the database on the server
Show dbs
Admin 0.000GB
Local 0.000GB
Master_slave 0.000GB
Wangshibo 0.000GB
2.2 switching databases
Switch to the wangshibo database (from the default test database)
Use wangshibo
Switched to db wangshibo
In mongo, db represents the database currently in use. In this way, db has changed from the original test to the current wangshibo database. If there is no such library, it will be created automatically.
2.3 View all collections in the current database
Show collections
Persons
Test
2.4 create a database
The use command is also used to create the database in mongo, and if the database name followed by use does not exist, mongo will create the new database.
However, in fact, only after the use command is executed, mongo will not create the database until you insert data into the database.
Use huanqiu
Switched to db huanqiu
Show dbs
Admin 0.000GB
Local 0.000GB
Master_slave 0.000GB
Wangshibo 0.000GB
I don't see the huanqiu database I just created here.
Db.huanqiu.insert ({"name": "testdb"})
WriteResult ({"nInserted": 1})
This creates a new hello collection in the huanqiu database and inserts a record into it.
Show dbs
Admin 0.000GB
Huanqiu 0.000GB
Local 0.000GB
Master_slave 0.000GB
Wangshibo 0.000GB
In this way, you can see that mongo did create a huanqiu database with a collection of hello.
2.5 Delete the database
Delete the current library. For example, if you have switched to the huanqiu library here, delete the huanku library.
Db.dropDatabase ()
{"dropped": "huanqiu", "ok": 1}
Show dbs
Admin 0.000GB
Local 0.000GB
Master_slave 0.000GB
Wangshibo 0.000GB
2.6 View the current database
Db
Huanqiu
Db.getName (); / / the above command is the same
Wangshibo
You can see that after deleting the huanqiu database, the current db still points to it, and only when the database is switched will the huanqiu disappear completely.
Use wangshibo
Switched to db wangshibo
Db
Wangshibo
Show dbs
Admin 0.000GB
Local 0.000GB
Master_slave 0.000GB
Wangshibo 0.000GB
2.6.1 repair the current database
Db.repairDatabase ()
{"ok": 1}
2.6.2 View current database status
Db.stats ()
{
"db": "wangshibo"
"collections": 3
"views": 0
"objects": 6
AvgObjSize: 75.5
"dataSize": 453
"storageSize": 73728
"numExtents": 0
"indexes": 4
"indexSize": 53248
"ok": 1
}
2.6.3 current db version
Db.version ()
3.4.4
2.6.4 View the address of the linked machine of the current db
Db.getMongo ()
Connection to 182.48.115.238:27017
2.6.5 Clone the database from the specified host
Db.cloneDatabase ("182.48.115.236")
{
"clonedColls": []
"ok": 0
"errmsg": "a collection 'wangshibo.wangshibo' already exists"
"code": 48
"codeName": "NamespaceExists"
}
2.6.6 copy the specified database data from the specified machine to a database
Copy the data of native master_slave to wangshibo database
Db.copyDatabase ("master_slave", "wangshibo", "127.0.0.1")
{"ok": 1}
3) collection level operation..
3.1 create a new collection
Db.createCollection ("Hello")
{"ok": 1}
Show collections
Hello
Wangshibo
Inserting data directly into a non-existent collection can also create a collection.
Db.hello2.insert ({"name": "lfqy"})
WriteResult ({"nInserted": 1})
Show collections
Hello
Hello2
Wangshibo
3.2Delete collection
Db.Hello.drop ()
True
If the true is returned, the deletion is successful, but the false is not.
Db.Hello.drop ()
False
There is no collection named hello, so deletion failed.
Rename collection
Rename the hello2 collection to HELLO
Show collections
Hello2
Wangshibo
Db.hello2.renameCollection ("HELLO")
{"ok": 1}
Show collections
HELLO
Wangshibo
3.4 View all collection in the current database
Show collections
HELLO
Wangshibo
Build an index on the HELLO collection, index the ID field, and 1 represents ascending order.
Db.HELLO.ensureIndex ({ID:1})
{
"createdCollectionAutomatically": false
"numIndexesBefore": 1
"numIndexesAfter": 2
"ok": 1
}
4) Record level operation..
4.1 insert operation
4.1.1 insert two records into the user collection
Db.user.insert ({'name':'GalGadot','gender':'female','age':28,'salary':11000})
WriteResult ({"nInserted": 1})
Db.user.insert ({'name':'Mikie Hara','gender':'female','age':26,'salary':7000})
WriteResult ({"nInserted": 1})
4.1.2 similar insertions can also be done with save
Db.user.save ({'name':'Wentworth Earl Miller','gender':'male','age':41,'salary':33000})
WriteResult ({"nInserted": 1})
4.2 find operation
4.2.1 find all records in the collection
Db.user.find ()
{"_ id": ObjectId ("59328c8aa7865327915046ae"), "name": "GalGadot", "gender": "female", "age": 28, "salary": 11000}
{"_ id": ObjectId ("59328c9da7865327915046af"), "name": "Mikie Hara", "gender": "female", "age": 26, "salary": 7000}
{"_ id": ObjectId ("59328cd6a7865327915046b0"), "name": "Wentworth Earl Miller", "gender": "male", "age": 41, "salary": 33000}
4.2.2 find eligible records in the collection
(1) single condition
Query data with an age of 26
Db.user.find ({"age": 26})
{"_ id": ObjectId ("59328c9da7865327915046af"), "name": "Mikie Hara", "gender": "female", "age": 26, "salary": 7000}
Query data with salary greater than 7000
Db.user.find ({salary: {$gt:7000}})
{"_ id": ObjectId ("59328c8aa7865327915046ae"), "name": "GalGadot", "gender": "female", "age": 28, "salary": 11000}
{"_ id": ObjectId ("59328cd6a7865327915046b0"), "name": "Wentworth Earl Miller", "gender": "male", "age": 41, "salary": 33000}
Query data containing 'ent'' in name
Db.user.find ({name:/ent/})
{"_ id": ObjectId ("59328cd6a7865327915046b0"), "name": "Wentworth Earl Miller", "gender": "male", "age": 41, "salary": 33000}
Query the data starting with G in name
Db.user.find ({name:/ ^ G /})
{"_ id": ObjectId ("59328c8aa7865327915046ae"), "name": "GalGadot", "gender": "female", "age": 28, "salary": 11000}
Query name data ending with t
Db.user.find ({name:/t$/})
{"_ id": ObjectId ("59328c8aa7865327915046ae"), "name": "GalGadot", "gender": "female", "age": 28, "salary": 11000}
(2) multiple conditions "and"
Query data with age less than 30 and more than 7000
Db.user.find ({age: {$lt:30}, salary: {$gt:7000}})
{"_ id": ObjectId ("59328c8aa7865327915046ae"), "name": "GalGadot", "gender": "female", "age": 28, "salary": 11000}
(3) multiple conditions "or"
Query records with age less than 30 or salary greater than 10000
Db.user.find ({$or: [{salary: {$gt:10000}}, {age: {$lt:30}}]})
{"_ id": ObjectId ("59328c8aa7865327915046ae"), "name": "GalGadot", "gender": "female", "age": 28, "salary": 11000}
{"_ id": ObjectId ("59328c9da7865327915046af"), "name": "Mikie Hara", "gender": "female", "age": 26, "salary": 7000}
{"_ id": ObjectId ("59328cd6a7865327915046b0"), "name": "Wentworth Earl Miller", "gender": "male", "age": 41, "salary": 33000}
4.2.3 query the first record
Replace the above find with findOne () to find the first record that meets the criteria.
Db.user.findOne ({$or: [{salary: {$gt:10000}}, {age: {$lt:25}}]})
{
"_ id": ObjectId ("59328c8aa7865327915046ae")
"name": "GalGadot"
"gender": "female"
"age": 28
"salary": 11000
}
4.2.4 query the specified field of a record
Query the name,age,salary,sex_orientation fields of all records in the user collection
Db.user.find ({}, {name:1,age:1,salary:1,sex_orientation:true})
{"_ id": ObjectId ("59328c8aa7865327915046ae"), "name": "GalGadot", "age": 28, "salary": 11000}
{"_ id": ObjectId ("59328c9da7865327915046af"), "name": "Mikie Hara", "age": 26, "salary": 7000}
{"_ id": ObjectId ("59328cd6a7865327915046b0"), "name": "Wentworth Earl Miller", "age": 41, "salary": 33000}
Note: the 1 here means to show the meaning of this column, or it can be expressed as true.
Db.user.find ({}, {name:1,age:1,salary:true,sex_orientation:1})
{"_ id": ObjectId ("59328c8aa7865327915046ae"), "name": "GalGadot", "age": 28, "salary": 11000}
{"_ id": ObjectId ("59328c9da7865327915046af"), "name": "Mikie Hara", "age": 26, "salary": 7000}
{"_ id": ObjectId ("59328cd6a7865327915046b0"), "name": "Wentworth Earl Miller", "age": 41, "salary": 33000}
4.2.5 query the data of the specified field and remove duplicates.
Query the data in the gender field and remove the duplicate data
Db.user.distinct ('gender')
["female", "male"]
4.2.6 Operations on query result sets
(1) Pretty Print
For convenience, mongo also provides pretty print tools, db.collection.pretty () or db.collection.forEach (printjson)
Db.user.find () .pretty ()
{
"_ id": ObjectId ("59328c8aa7865327915046ae")
"name": "GalGadot"
"gender": "female"
"age": 28
"salary": 11000
}
{
"_ id": ObjectId ("59328c9da7865327915046af")
"name": "Mikie Hara"
"gender": "female"
"age": 26
"salary": 7000
}
{
"_ id": ObjectId ("59328cd6a7865327915046b0")
"name": "Wentworth Earl Miller"
"gender": "male"
"age": 41
"salary": 33000
}
(2) specify the entries displayed by the result set
A) display the first three records in the result set
Db.user.find (). Limit (3)
{"_ id": ObjectId ("59328c8aa7865327915046ae"), "name": "GalGadot", "gender": "female", "age": 28, "salary": 11000}
{"_ id": ObjectId ("59328c9da7865327915046af"), "name": "Mikie Hara", "gender": "female", "age": 26, "salary": 7000}
{"_ id": ObjectId ("59328cd6a7865327915046b0"), "name": "Wentworth Earl Miller", "gender": "male", "age": 41, "salary": 33000}
B) query all data after article 1
Db.user.find () .skip (1)
{"_ id": ObjectId ("59328c9da7865327915046af"), "name": "Mikie Hara", "gender": "female", "age": 26, "salary": 7000}
{"_ id": ObjectId ("59328cd6a7865327915046b0"), "name": "Wentworth Earl Miller", "gender": "male", "age": 41, "salary": 33000}
Query all data after skipping the first two items
Db.user.find (). Skip (2)
{"_ id": ObjectId ("59328cd6a7865327915046b0"), "name": "Wentworth Earl Miller", "gender": "male", "age": 41, "salary": 33000}
C) sort the result set
Ascending order
Db.user.find () .sort ({salary:1})
{"_ id": ObjectId ("59328c9da7865327915046af"), "name": "Mikie Hara", "gender": "female", "age": 26, "salary": 7000}
{"_ id": ObjectId ("59328c8aa7865327915046ae"), "name": "GalGadot", "gender": "female", "age": 28, "salary": 11000}
{"_ id": ObjectId ("59328cd6a7865327915046b0"), "name": "Wentworth Earl Miller", "gender": "male", "age": 41, "salary": 33000}
Descending order
Db.user.find () .sort ({salary:-1})
{"_ id": ObjectId ("59328cd6a7865327915046b0"), "name": "Wentworth Earl Miller", "gender": "male", "age": 41, "salary": 33000}
{"_ id": ObjectId ("59328c8aa7865327915046ae"), "name": "GalGadot", "gender": "female", "age": 28, "salary": 11000}
{"_ id": ObjectId ("59328c9da7865327915046af"), "name": "Mikie Hara", "gender": "female", "age": 26, "salary": 7000}
4.2.7 count the number of entries recorded in the query results
(1) Statistics of all records in the set
Db.user.find () .count ()
three
(2) query the number of records that meet the criteria
Query the number of records whose salary is less than 4000 or greater than 10000
Db.user.find ({$or: [{salary: {$lt:4000}}, {salary: {$gt:10000}}]}) .count ()
two
4.3 Delete operation
4.3.1 Delete all data in the entire collection
Db.wangshibo.find ()
{"_ id": ObjectId ("5932683b156e298477cdf3ad"), "name": "Rookie tutorial"}
Db.wangshibo.remove ({})
WriteResult ({"nRemoved": 1})
Db.wangshibo.find ()
It can be seen that all records in the wangshibo have been deleted.
Mongo does not support all when deleting data * Delete all and choose {} to delete them all.
You can use the remove () function to delete data from the mongodb collection. The remove () function accepts a query document as an optional parameter to selectively delete eligible documents.
The remove () function does not delete the collection itself, nor will the original index be deleted.
Deleting a document is permanent, cannot be undone, and cannot be restored. Therefore, it is a good habit to use the find () command to see if it is correct before executing the remove () function.
Note the difference between db.collection.remove () and drop (). Remove () simply deletes all the records in the collection, while the original index and other information in the collection is still there, and
Drop () removes the entire collection-related information (including the index).
4.3.2 Delete all eligible records in the collection
Db.user.find ()
{"_ id": ObjectId ("59328c8aa7865327915046ae"), "name": "GalGadot", "gender": "female", "age": 28, "salary": 11000}
{"_ id": ObjectId ("59328c9da7865327915046af"), "name": "Mikie Hara", "gender": "female", "age": 26, "salary": 7000}
{"_ id": ObjectId ("59328cd6a7865327915046b0"), "name": "Wentworth Earl Miller", "gender": "male", "age": 41, "salary": 33000}
Db.user.remove ({name:'GalGadot'})
WriteResult ({"nRemoved": 1})
Db.user.find ()
{"_ id": ObjectId ("59328c9da7865327915046af"), "name": "Mikie Hara", "gender": "female", "age": 26, "salary": 7000}
{"_ id": ObjectId ("59328cd6a7865327915046b0"), "name": "Wentworth Earl Miller", "gender": "male", "age": 41, "salary": 33000}
4.3.3 Delete a qualified record in the collection
Db.user.find ()
{"_ id": ObjectId ("59328c9da7865327915046af"), "name": "Mikie Hara", "gender": "female", "age": 26, "salary": 7000}
{"_ id": ObjectId ("59328cd6a7865327915046b0"), "name": "Wentworth Earl Miller", "gender": "male", "age": 41, "salary": 33000}
Db.user.remove ({salary: {$lt:30000}}, 1)
WriteResult ({"nRemoved": 1})
Db.user.find ()
{"_ id": ObjectId ("59328cd6a7865327915046b0"), "name": "Wentworth Earl Miller", "gender": "male", "age": 41, "salary": 33000}
Of course, it can also be a command: db.user.remove ({salary: {$lt:30000}}, true), because true and 1 mean the same thing.
4.4 Update operation
4.4.1 assignment update
Db.collection.update (criteria, objNew, upsert, multi)
The query condition of criteria:update, which is similar to the one after where in sql update query
Objects for objNew:update and some updated operators (such as $, $inc...) And so on, can also be understood as after the set in the sql update query.
Upsert: if there is no record of update, whether to insert objNew,true is insert. Default is false, not inserted.
Multi: mongodb defaults to false. Only the first record found is updated. If this parameter is true, multiple records are updated by item.
Db.user.find ()
{"_ id": ObjectId ("59328cd6a7865327915046b0"), "name": "Wentworth Earl Miller", "gender": "male", "age": 41, "salary": 33000}
{"_ id": ObjectId ("593293e2a7865327915046b2"), "name": "GalGadot", "gender": "female", "age": 28, "salary": 11000}
{"_ id": ObjectId ("593293f0a7865327915046b3"), "name": "Gasdfdst", "gender": "female", "age": 58, "salary": 60000}
{"_ id": ObjectId ("59329401a7865327915046b4"), "name": "huihui", "gender": "female", "age": 18, "salary": 23100}
Db.user.update ({name:'huihui'}, {$set: {age:23}}, false,true)
WriteResult ({"nMatched": 1, "nUpserted": 0, "nModified": 1})
Db.user.find ()
{"_ id": ObjectId ("59328cd6a7865327915046b0"), "name": "Wentworth Earl Miller", "gender": "male", "age": 41, "salary": 33000}
{"_ id": ObjectId ("593293e2a7865327915046b2"), "name": "GalGadot", "gender": "female", "age": 28, "salary": 11000}
{"_ id": ObjectId ("593293f0a7865327915046b3"), "name": "Gasdfdst", "gender": "female", "age": 58, "salary": 60000}
{"_ id": ObjectId ("59329401a7865327915046b4"), "name": "huihui", "gender": "female", "age": 23, "salary": 23100}
Db.user.update ({name:'lfqy1'}, {$set: {age:23}}, true,true)
WriteResult ({
"nMatched": 0
"nUpserted": 1
"nModified": 0
"_ id": ObjectId ("5932946c9758703fe04b0f73")
})
Db.user.find ()
{"_ id": ObjectId ("59328cd6a7865327915046b0"), "name": "Wentworth Earl Miller", "gender": "male", "age": 41, "salary": 33000}
{"_ id": ObjectId ("593293e2a7865327915046b2"), "name": "GalGadot", "gender": "female", "age": 28, "salary": 11000}
{"_ id": ObjectId ("593293f0a7865327915046b3"), "name": "Gasdfdst", "gender": "female", "age": 58, "salary": 60000}
{"_ id": ObjectId ("59329401a7865327915046b4"), "name": "huihui", "gender": "female", "age": 23, "salary": 23100}
{"_ id": ObjectId ("5932946c9758703fe04b0f73"), "name": "lfqy1", "age": 23}
4.4.2 value-added updates
Db.user.find ()
{"_ id": ObjectId ("52453cfb25e437dfea8fd4f4"), "name": "Gal Gadot", "gender": "female", "age": 28, "salary": 11000}
{"_ id": ObjectId ("52453d8525e437dfea8fd4f5"), "name": "Mikie Hara", "gender": "female", "age": 26, "salary": 7000}
{"_ id": ObjectId ("52453e2125e437dfea8fd4f6"), "name": "Wentworth Earl Miller", "gender": "male", "age": 41, "salary": 33000}
{"_ id": ObjectId ("52454155d8947fb70d000000"), "name": "not known", "sex_orientation": "male", "age": 13, "salary": 30000}
{"_ id": ObjectId ("5245610881c83a5bf26fc285"), "age": 23, "name": "lfqy1"}
{"_ id": ObjectId ("52455f8925e437dfea8fd4fd"), "age": 23, "gender": "male", "interest": "NBA", "name": "lfqy", "salary": 1}
{"_ id": ObjectId ("5245607525e437dfea8fd4fe"), "age": 23, "gender": "male", "interest": "NBA", "name": "lfqy", "salary": 2}
Db.user.update ({gender:'female'}, {$inc: {salary:50}}, false,true)
Db.user.find ()
{"_ id": ObjectId ("52453cfb25e437dfea8fd4f4"), "name": "Gal Gadot", "gender": "female", "age": 28, "salary": 11050}
{"_ id": ObjectId ("52453d8525e437dfea8fd4f5"), "name": "Mikie Hara", "gender": "female", "age": 26, "salary": 7050}
{"_ id": ObjectId ("52453e2125e437dfea8fd4f6"), "name": "Wentworth Earl Miller", "gender": "male", "age": 41, "salary": 33000}
{"_ id": ObjectId ("52454155d8947fb70d000000"), "name": "not known", "sex_orientation": "male", "age": 13, "salary": 30000}
{"_ id": ObjectId ("5245610881c83a5bf26fc285"), "age": 23, "name": "lfqy1"}
{"_ id": ObjectId ("52455f8925e437dfea8fd4fd"), "age": 23, "gender": "male", "interest": "NBA", "name": "lfqy", "salary": 1}
{"_ id": ObjectId ("5245607525e437dfea8fd4fe"), "age": 23, "gender": "male", "interest": "NBA", "name": "lfqy", "salary": 2}
With regard to the update operation (db.collection.update (criteria, objNew, upsert, multi), it is important to note that if upsert is true, if the update condition is not found, mongo will insert a record in the collection whose value meets the update condition (where the field has only the fields involved in the update condition, and the value of the field meets the update condition), and then update it (note If the update condition is an inequality condition such as $lt, then upsert insert
Other command actions:
1. Create an aggregate collection (table)
Db.createCollection ("collName", {size: 20, capped: 5, max: 100}); / / if created successfully, {"ok": 1} will be displayed.
/ / determine whether the set is a fixed capacity db.collName.isCapped ()
2. Get the aggregate set with the specified name (table)
Db.getCollection ("account")
3. Get all the aggregate sets of the current db
Db.getCollectionNames ()
4. Display the status of all clustered indexes in the current db
Db.printCollectionStats ()
III. User relevance
1. Add a user
Db.addUser ("name")
Db.addUser ("userName", "pwd123", true); add user, set password, read-only or not
2. Database authentication and security mode
Db.auth ("userName", "123123")
3. Show all current users
Show users
4. Delete a user
Db.removeUser ("userName")
IV. Aggregate collection query
1. Query all records
Db.userInfo.find ()
Equivalent to: select* from userInfo
By default, 20 records are displayed per page, and when the display is not low, you can use the it iterative command to query the next page of data. Note: you cannot type the it command with ";"
But you can set the size of the data displayed on each page, using DBQuery.shellBatchSize= 50; that will show 50 records per page.
2. After the query is removed, the duplicate data of a column in the current aggregate collection is removed.
Db.userInfo.distinct ("name")
Will filter out the same data in name
Equivalent to: select distict name from userInfo
3. Query the records with age = 22
Db.userInfo.find ({"age": 22})
Equivalent to: select * from userInfo where age = 22
4. Query the records with age > 22
Db.userInfo.find ({age: {$gt: 22}})
Equivalent to: select * from userInfo where age > 22
5. Query age
< 22的记录 db.userInfo.find({age: {$lt: 22}}); 相当于:select * from userInfo where age = 25的记录 db.userInfo.find({age: {$gte: 25}}); 相当于:select * from userInfo where age >= 25
7. Query age = 23 and age 25
Db.userInfo.find ({age: {$gt: 25}}, {name: 1, age: 1})
Equivalent to: select name, age from userInfo where age > 25
13. Sort by age
Ascending order: db.userInfo.find () .sort ({age: 1})
Descending order: db.userInfo.find () .sort ({age:-1})
14. Query the data of name = zhangsan, age = 22
Db.userInfo.find ({name: 'zhangsan', age: 22})
Equivalent to: select * from userInfo where name = 'zhangsan' and age =' 22'
15. Query the first five pieces of data
Db.userInfo.find () .limit (5)
Equivalent to: selecttop 5 * from userInfo
16. Query the data after 10 items
Db.userInfo.find (). Skip (10)
Equivalent to: select from userInfo where id not in (
Selecttop 10 from userInfo
);
17. Query data between 5 and 10
Db.userInfo.find () .limit (10) .skip (5)
Can be used for paging, limit is the page of pageSize,skip * pageSize
18. Or and query
Db.userInfo.find ({$or: [{age: 22}, {age: 25}]})
Equivalent to: select * from userInfo where age = 22 or age = 25
19. Query the first piece of data
Db.userInfo.findOne ()
Equivalent to: selecttop 1 * from userInfo
Db.userInfo.find () .limit (1)
20. Query the number of records in a result set
Db.userInfo.find ({age: {$gte: 25}}) .count ()
Equivalent to: select count (*) from userInfo where age > = 20
21. Sort by a column
Db.userInfo.find ({sex: {$exists: true}}) .count ()
Equivalent to: select count (sex) from userInfo
5. Index
1. Create an index
Db.userInfo.ensureIndex ({name: 1})
Db.userInfo.ensureIndex ({name: 1, ts:-1})
2. Query all indexes of the current cluster
Db.userInfo.getIndexes ()
3. View the total index record size
Db.userInfo.totalIndexSize ()
4. Read all the index information of the current collection
Db.users.reIndex ()
5. Delete the specified index
Db.users.dropIndex ("name_1")
6. Delete all indexes
Db.users.dropIndexes ()
VI. Modify, add and delete collection data
1. Add
Db.users.save ({name: 'zhangsan', age: 25, sex: true})
The data column of the added data, which is not fixed, according to the added data.
2. Modification
Db.users.update ({age: 25}, {$set: {name: 'changeName'}}, false, true)
Equivalent to: update users set name = 'changeName' where age = 25
Db.users.update ({name: 'Lisi'}, {$inc: {age: 50}}, false, true)
Equivalent to: update users set age = age + 50 where name = 'Lisi'
Db.users.update ({name: 'Lisi'}, {$inc: {age: 50}, $set: {name:' hoho'}}, false, true)
Equivalent to: update users set age = age + 50, name = 'hoho' where name =' Lisi'
3. Delete
Db.users.remove ({age: 132})
4. Query modification and deletion
Db.users.findAndModify ({
Query: {age: {$gte: 25}}
Sort: {age:-1}
Update: {$set: {name: 'a2'}, $inc: {age: 2}}
Remove: true
});
Db.runCommand ({findandmodify: "users"
Query: {age: {$gte: 25}}
Sort: {age:-1}
Update: {$set: {name: 'a2'}, $inc: {age: 2}}
Remove: true
});
Either update or remove is a required parameter; the other parameters are optional.
Parameter detailed definition default value
Query query filter criteria {}
Sort if multiple documents meet the query filtering criteria, the first object will be selected in the arrangement specified by this parameter, and the object will be manipulated {}
If remove is true, the selected object will be deleted before being returned.
Update a modifier object
N/A
If new is true, the modified object is returned instead of the original object. This parameter is ignored during the delete operation. False
For fields, see Retrieving a Subset of Fields (1.5.0 +)
All fields
Upsert creates a new object if the query result is empty. Example (1.5.4+)
False
7. Statement block operation
1. Simple Hello World
Print ("Hello World!")
This way of writing calls the print function and writes "Hello World!" directly. The effect is the same.
2. Convert an object to json
Tojson (new Object ())
Tojson (new Object ('a'))
3. Add data in a loop
For (var I = 0; I < 30; iTunes +) {
... Db.users.save ({name: "u _" + I, age: 22 + I, sex: I% 2})
...}
In this way, 30 pieces of data are added cyclically, and the writing of parentheses can also be omitted.
For (var I = 0; I < 30; iTunes +) db.users.save ({name: "u _" + I, age: 22 + I, sex: I% 2})
It is also possible to use it to view the information on the next page when you use db.users.find () to query and display multiple pieces of data but not one page.
4. Find cursor query
Var cursor = db.users.find ()
While (cursor.hasNext ()) {
Printjson (cursor.next ())
}
In this way, all the users information can be queried, and it can be written the same way.
Var cursor = db.users.find ()
While (cursor.hasNext ()) {printjson (cursor.next);}
You can also omit the {} sign
5. ForEach iterative cycle
Db.users.find () forEach (printjson)
A function must be passed in forEach to process the data information of each iteration.
6. Treat find cursors as arrays
Var cursor = db.users.find ()
Cursor [4]
Get the data with a subscript index of 4
Now that you can treat it as an array, you can get its length: cursor.length (); or cursor.count ()
Then we can also display the data in a loop.
For (var I = 0, len = c.length (); I < len; iTunes +) printjson (c [I])
7. Convert find cursors to arrays
Var arr = db.users.find () .toArray ()
Printjson (arr [2])
Convert it to an array with the toArray method
8. Customize our own query results
Show only age
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.