Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Installation and startup configuration of Mongodb under Linux

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)06/01 Report--

MongoDB is a product between relational database and non-relational database, which is the most functional and most like relational database in non-relational database. The data structure he supports is very loose, which is similar to json's bjson format, so it can store more complex data types. The most important feature of Mongo is that the query language it supports is very powerful, and its syntax is somewhat similar to the object-oriented query language. It can almost achieve most of the functions similar to the single table query of relational database, and also supports the establishment of data indexing.

It is characterized by high performance, easy to deploy, easy to use, and it is very convenient to store data. The main functional features are:

For collection storage, it is easy to store data of object type.

Mode freedom.

Dynamic query is supported.

Full indexing is supported, including internal objects.

Query is supported.

Replication and failure recovery are supported.

Use efficient binary data storage, including large objects such as video, etc.

Automatically handle fragments to support scalability at the cloud computing level

Support for RUBY,PYTHON,JAVA,C++,PHP and other languages.

The file is stored in BSON (an extension of JSON)

Accessible through the network

The so-called "Collenction-Orented-oriented" means that data is grouped and stored in a dataset, which is called a Collenction. Each collection has a unique identification name in the database and can contain an unlimited number of documents. The concept of a collection is similar to a table (table) in a relational database (RDBMS), except that it does not need to define any schema.

Schema freedom (schema-free) means that we do not need to know any structural definition of the file stored in the mongodb database. If necessary, you can store files with different structures in the same database.

A document stored in a collection is stored as a key-value pair. The key is used to uniquely identify a document that is a string type, while the value can be a complex file type. We call this form of storage BSON (Binary Serialized dOcument Format).

Download address of MongoDB official website: http://www.mongodb.org/downloads

[root@localhost app] # tar zxvf mongodb-linux-x86_64-3.4.3.tgz mongodb-linux-x86_64-3.4.3/READMEmongodb-linux-x86_64-3.4.3/THIRD-PARTY-NOTICESmongodb-linux-x86_64-3.4.3/MPL-2mongodb-linux-x86_64-3.4.3/GNU-AGPL-3.0mongodb-linux-x86_64-3.4.3/bin/mongodumpmongodb-linux-x86_64-3.4. 3/bin/mongorestoremongodb-linux-x86_64-3.4.3/bin/mongoexportmongodb-linux-x86_64-3.4.3/bin/mongoimportmongodb-linux-x86_64-3.4.3/bin/mongostatmongodb-linux-x86_64-3.4.3/bin/mongotopmongodb-linux-x86_64-3.4.3/bin/bsondumpmongodb-linux-x86_64-3.4.3/bin/mongofilesmongodb-linux-x86_64-3.4.3 Universe MongoplogmongodbKlinux- X86'64-3.4.3/bin/mongoreplaymongodb-linux-x86_64-3.4.3/bin/mongoperfmongodb-linux-x86_64-3.4.3/bin/mongodmongodb-linux-x86_64-3.4.3/bin/mongosmongodb-linux-x86_64-3.4.3/bin/mongo [root@localhost app] # mv mongodb-linux-x86_64-3.4.3 mongodb [root@localhost app] # cd mongodb [root@localhost mongodb] # lsbin GNU-AGPL- 3.0 MPL-2 README THIRD-PARTY-NOTICES [root@localhost mongodb] # mkdir data [root@localhost mongodb] # mkdir logs [root@localhost mongodb] # lsbin data GNU-AGPL-3.0 logs MPL-2 README THIRD-PARTY-NOTICES [root@localhost mongodb] # cd logs/ [root@localhost logs] # touch mongodb.log [root@localhost logs] # cd.. / bin/ [root@localhost bin] # lsbsondump mongo mongod mongodump mongoexport mongofiles mongoimport mongooplog mongoperf mongoreplay mongorestore mongos mongostat mongotop [root@localhost bin] #. / mongod-port 10001-dbpath=/app/mongodb/data/-logpath=/app/mongodb/logs/-logappend2017-04-13T10:18:16.690+0800 F CONTROL [main] Failed global initialization: FileNotOpen: logpath "/ app/mongodb/logs/" should name a file Not a directory. [root@localhost bin] #. / mongod-port 10001-- dbpath=/app/mongodb/data/-- logpath=/app/mongodb/logs/mongodb.log-- logappend # launch [root@localhost bin]. / mongod-port 10001-- dbpath=/app/mongodb/data/-- logpath=/app/mongodb/logs/mongodb.log-- logappend-- fork # launch about to fork child process in the background, waiting until server is ready for connections.forked process: 19542child process started successfully Parent exiting [root@localhost mongodb] # cd data/ [root@localhost data] # lscollection-0-338357810244237439.wt diagnostic.data index-3-338357810244237439.wt journal mongod.lock storage.bson WiredTigerLAS.wt WiredTiger.turtlecollection-2-338357810244237439.wt index-1-338357810244237439.wt index-4-338357810244237439.wt _ mdb_catalog.wt sizeStorer.wt WiredTiger WiredTiger.lock WiredTiger.wt [root@localhost data] # ps-ef | grep-I mongoroot 19542 10 10:43? 00:00:07. / mongod-port 10001-dbpath=/app/mongodb/data/-- logpath=/app/mongodb/logs/mongodb.log-- logappend-- forkroot 19598 7588 0 10:58 pts/1 00:00:00 grep-I mongo [root@localhost bin] #

-dbpath database path (data file)

-- logpath log file path

-- master designated as the master machine

-- slave specified as slave machine

-- source specifies the IP address of the host machine

-- pologSize specifies that the log file size does not exceed 64m. Because resync is very heavy and time-consuming, it is best to avoid resync by setting a large enough oplogSize (the default oplog size is 5% of the free disk size).

-- add at the end of the logappend log file

-- port enables the port number. If not specified, it defaults to 27017.

-- fork runs in the background

-- only specifies which database to replicate

-- slavedelay refers to the time interval detected from replication

-- whether auth needs to verify permission login (username and password)

[root@localhost bin] #. / mongod-h-quiet # quiet output-- port arg # specifies the service port number. The default port 27017--bind_ip arg # binds the service IP. If 127.0.0.1 is bound, it can only be accessed locally. No default local IP--logpath arg # specifies the MongoDB log file. Note that the specified file is not a directory-- logappend # writes the log by append-- the full path of pidfilepath arg # PID File. If not, there is no PID file-- the full path of the private key of the keyFile arg # cluster. It is only valid for the Replica Set architecture-- unixSocketPrefix arg # UNIX domain socket replacement directory, (default is / tmp)-- fork # runs MongoDB as a daemon Create server process-- auth # enable authentication-- cpu # periodically display CPU utilization of CPU and iowait--dbpath arg # specify database path-- diaglog arg # diaglog option 0=off 1 "W2R 3=both 7=W+some reads--directoryperdb # Settings each database will be saved in a separate directory-- journal # enable logging option MongoDB's data operations will be written to files in the journal folder-- journalOptions arg # enable log diagnostics option-- ipv6 # enable IPv6 option-- jsonp # allow JSONP access through HTTP (with security implications)-- maxConns arg # maximum number of simultaneous connections default 2000--noauth # does not enable authentication-- nohttpinterface # shuts down the http interface Turn off port 27018 access by default-noprealloc # disable data file pre-allocation (often affecting performance)-noscripting # disable scripting engine-notablescan # do not allow table scanning-nounixsocket # disable Unix socket snooping-nssize arg (= 16) # set letter database .ns file size (MB)-objcheck # check the validity when receiving customer data -- profile arg # Archive parameter 0=off 1=slow, 2=all--quota # limit the number of files per database Set the default to 8--quotaFiles arg # number of files allower per db, requires-- quota--rest # Open simple rest API--repair # repair all databases run repair on all dbs--repairpath arg # repair the directory of files generated by the library Default is directory name dbpath--slowms arg (= 100) # value of slow for profile and console log--smallfiles # use a smaller default file-- syncdelay arg (= 60) # number of seconds the data was written to disk (0=never (not recommended)-- sysinfo # print some diagnostic system information-- upgrade # if you need to upgrade the database * Replicaton parameter-- -fastsync # enable replication from the library from a dbpath The database of the dbpath is a snapshot of the master library and can be used to quickly enable synchronization-autoresync # automatically resynchronize if the synchronization data between the slave library and the master library is much worse -- oplogSize arg # sets the size of oplog (MB) * master / slave parameters-master # master library mode-- Slave # slave library mode-- source arg # slave library port number-- only arg # specifies a single database replication-- slavedelay arg # sets the delay time for synchronizing the master database from the slave library * Replica set (replica set) option:-- -- replSet arg # set replica set name * Sharding (sharding) option- -configsvr # declares that this is a clustered config service Default port 27019 The default directory / data/configdb--shardsvr # declares that this is a cluster shard, and the default port 27018--noMoveParanoia # turns off paranoia for moveChunk data preservation [root@localhost bin] #

The above parameters can be written into the mongod.conf configuration document, for example:

Dbpath = / data/mongodb

Logpath = / data/mongodb/mongodb.log

Logappend = true

Port = 27017

Fork = true

Auth = true

Connect mongodb

[root@localhost bin] # / mongo-- port 10001MongoDB shell version v3.4.3connecting to: mongodb://127.0.0.1:10001/MongoDB server version: 3.4.3Welcome 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-userServer has startup warnings: 2017-04-13T10:43:51.043+0800 I STORAGE [initandlisten] 2017-04-13T10:43:51.043+0800 I STORAGE [initandlisten] * * WARNING: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine2017-04-13T10:43:51.043+0800 I STORAGE [initandlisten] * * See http://dochub.mongodb.org/core/prodnotes-filesystem2017-04- 13T10:43:52.492+0800 I CONTROL 2017-04-13T10:43:52.508+0800 I CONTROL [initandlisten] * * WARNING: Access control is not enabled for the database.2017-04-13T10:43:52.508+0800 I CONTROL [initandlisten] * * Read and write access to data and configuration is unrestricted.2017-04-13T10:43:52.508+0800 I CONTROL [initandlisten] * * WARNING: You are running this process as the root user Which is not recommended.2017-04-13T10:43:52.508+0800 I CONTROL [initandlisten] 2017-04-13T10:43:52.509+0800 I CONTROL [initandlisten] 2017-04-13T10:43:52.509+0800 I CONTROL [initandlisten] * * WARNING: soft rlimits too low. Rlimits set to 1818 processes, 65535 files. Number of processes should be at least 32767.5: 0.5 times number of files. > use test;switched to db test >

If the database cannot be connected, it is a problem with the mongod.lock file in the data directory. You can use the following repair command

[root@localhost bin] # / mongod-- repair2017-04-14T10:40:50.902+0800 I CONTROL [initandlisten] MongoDB starting: pid=23422 port=27017 dbpath=/data/db 64-bit host=localhost.localdomain2017-04-14T10:40:50.902+0800 I CONTROL [initandlisten] db version v3.4.32017-04-14T10:40:50.902+0800 I CONTROL [initandlisten] git version: f07437fb5a6cca07c10bafa78365456eb1d6d5e12017-04-14T10:40:50.902+0800 I CONTROL [initandlisten] allocator: tcmalloc2017-04-14T10:40:50.902+0800 I CONTROL [initandlisten] modules: none2017-04-14T10:40:50.902+0800 I CONTROL [initandlisten] build environment:2017-04-14T10:40:50.902+0800 I CONTROL [initandlisten] distarch: x86142017-04-14T10:40:50.902+0800 I CONTROL [initandlisten] target_arch: x86142017-04-14T10:40:50.902+0800 I CONTROL [initandlisten] options: {repair: true} 2017-04-14T10:40:50.926+0800 I STORAGE [initandlisten] exception in initAndListen: 29 Data directory / data/db not found. Terminating2017-04-14T10:40:50.926+0800 I NETWORK [initandlisten] shutdown: going to close listening sockets...2017-04-14T10:40:50.926+0800 I NETWORK [initandlisten] shutdown: going to flush diaglog...2017-04-14T10:40:50.928+0800 I CONTROL [initandlisten] now exiting2017-04-14T10:40:50.928+0800 I CONTROL [initandlisten] shutting down with code:100 [root@localhost bin] #

Configure Mongodb through a configuration file

[root@localhost /] # cd / app/mongodb [root@localhost mongodb] # lsbin data GNU-AGPL-3.0 logs MPL-2 README THIRD-PARTY-NOTICES [root@localhost mongodb] # mkdir etc [root@localhost mongodb] # mkdir pid [root@localhost mongodb] # touch etc/mongodb.conf [root@localhost mongodb] # vim etc/mongodb.conf port=10001dbpath=/app/mongodb/data/logpath=/app/mongodb/mongodb.loglogappend=truemaxConns=20000fork=truepidfilepath=/app/mongodb/pid/mongodb.pidoplogSize=10240directoryperdb=true [root@localhost mongodb] # bin/mongod-f etc/mongodb.conf about to fork child process Waiting until server is ready for connections.forked process: 23503child process started successfully, parent exiting [root@localhost mongodb] # lsof-I: 10001COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAMEmongod 23503 root 7u IPv4 69427 0t0 TCP *: scp-config (LISTEN) [root@localhost mongodb] #

Add mongodb to the service and manage it as a service

[root@localhost app] # cat mongodb.sh #! / bin/bash#chkconfig: 2345 10 90#description: Mongodb server is.# source function librarysource / etc/rc.d/init.d/functionsport=10001pidfile= "/ app/mongodb/pid/mongodb.pid" lockfile= "/ var/lock/subsys/mongodb-server" rootpath= "/ app/mongodb/" config= / app/mongodb/etc/mongodb.conf "binpath=" / app/mongodb/bin "[- r" $SYSCONFIG "] & & source" $SYSCONFIG "status1 () {local base pid pid_file= if ["$#" = 0] Then echo $"Usage: status [- p pidfile] {program}" return 1 fi if ["$1" = "- p"] Then pid_file=$2 shift 2 fi base=$ {1customers /} # First try "pidof" _ _ pids_var_run "$1"$pid_file" RC=$? If [- z "$pid_file"-a-z "$pid"]; then pid= "$(_ _ pids_pidof" $1 ")" fi if [- n "$pid"]; then# echo $"${base} (pid $pid) is running..." Echo $"${base} (port $port) is running..." Return 0 fi case "$RC" in 0) # echo $"${base} (pid $pid) is running..." Echo $"${base} (port $port) is running..." Return 0;; 1) echo $"${base} dead but pid file exists" return 1;; esac if [- f / var/lock/subsys/$ {base}] Then echo $"${base} dead but subsys locked" return 2 fi echo $"${base} is stopped" return 2} reids_status () {status1-p $pidfile mongod} start () {if [- e $pidfile]; then echo "Mongodb Server [port $port] aleady running." Exit 1 else echo-n "Mongodb Server [port $I] is starting [" $binpath/mongod-f $config > / tmp/mongod.txt value=$? [$value-eq 0] & & touch $lockfile & & echo-e "\ 033 [32m OK\ 033 [0m]" cat / tmp/mongod.txt return $value Fi} stop () {echo-n "Stop Mongodb Server [port $port]." Killproc-p $pidfile mongod & & echo "Mongodb Server [port $port] has stopped" [$?-eq 0] & & rm-rf $lockfile $pidfile} restart () {stop start} case "$1" instart) start;;stop) stop;;restart) restart;;status) reids_status *) echo $"Usage: $0 {start | stop | restart | status}" esac [root@localhost app] # cp mongodb.sh / etc/rc.d/init.d/mongodb [root@localhost app] # chmod + x / etc/rc.d/init.d/mongodb [root@localhost app] # chkconfig-add mongodb [root@localhost app] # chkconfig-level 2345 mongodb on [root@localhost app] # service mongodb statusmongod (port 10001) is running... [root@localhost app] # service mongodb stopMongodb Server [port 10001] has stopped [OK] [root@localhost app] # service mongodb startMongodb Server [port] is starting [OK] about to fork child process Waiting until server is ready for connections.forked process: 2416child process started successfully, parent exiting [root@localhost app] # service mongodb statusmongod (port 10001) is running... [root@localhost app] #

MongoDB's Syslog starts cutting

You can use the system's logrotate log auto-slicing service to change the size of the mongos.log file, go to the cd / etc/logrotate.d/ directory, create a file: touch mongos, and edit and add the following:

[root@localhost logrotate.d] # cat / opt/mongodb-3.4.6/conf/mongodb.conf bind_ip = 0.0.0.0port = 9981fork = truedbpath = / opt/mongodb-3.4.6/datapidfilepath = / var/run/mongod.pidlogpath = / opt/mongodb-3.4.6/logs/mongod.loglogappend = trueauth = true [root@localhost logrotate.d] # cat / etc/logrotate.d/mongos / opt/mongodb-3.4.6/logs/mongod.log { Rotate 1 daily dateext size 100K postrotate / usr/bin/kill-SIGUSR1 `/ var/run/mongod.pid 2 > / dev/ null`2 > / dev/null | | true endscript} [root@localhost logrotate.d] #

Size: specifies that mongos.log files are automatically cut when they exceed 200m

Dateext: specifies how backup files are named when cutting files

Rotate 5: five archive logs will be stored at a time. For the sixth archive, the oldest archive will be deleted.

Daily: log files will be polled by day

Postrotate/endscript: when the other commands are executed, execute the commands in this one

Frequently asked questions:

Exception: exception in initAndListen: 12596 old lock file, terminating

Reason: the lock was not released before shutting down Mongodb, causing the restart to fail

Solution: delete the mongodb.lock file (usually in the data directory) and restart it.

Note: when backing up a database with mongodump, you cannot use fsync and locks, otherwise dump programs cannot connect to the database server. In other cases, fsync and locks are used. It should be noted that the operation may take a long time.

Basic usage of database

Show dbs: displaying a list of databases

Show collections: displays collections in the current database (similar to tables in a relational database)

Show users: displaying users

Use: switch the current database, which is the same as in MS-SQL

Db.help (): displays database operation commands, with many commands in it

Db.foo.help (): show collection operation commands. There are also many commands. Foo refers to a collection called foo under the current database, not a real command.

Db.foo.find (): performs a data lookup for the foo collection in the current database (all data is listed because there are no conditions)

Db.foo.find ({a: 1}): looks up the foo collection in the current database if there is an attribute in the data called an and the value of an is 1

MongoDB does not have a command to create a database, but there are similar commands.

For example, if you want to create a "myTest" database, first run the use myTest command, and then do some operations (such as: db.createCollection ('user')), so you can create a database called "myTest".

Database common commands

1. Help view command prompts

Help

Db.help ()

Db.yourColl.help ()

Db.youColl.find () .help ()

Rs.help ()

2. Switch / create database

Use yourDB; automatically creates the current database when you create a collection (table)

3. Query all databases

Show dbs

4. Delete the database currently in use

Db.dropDatabase ()

5. Clone the database from the specified host

Db.cloneDatabase ("127.0.0.1"); Clones the data from the database on the specified machine to the current database

6. Copy the specified database data from the specified machine to a database

Db.copyDatabase ("mydb", "temp", "127.0.0.1"); copy the local mydb data to the temp database

7. Repair the current database

Db.repairDatabase ()

8. View the database currently in use

Db.getName ()

The db; db and getName methods have the same effect, and both can query the currently used database.

9. Display the current db status

Db.stats ()

10. Current db version

Db.version ()

11. Check the address of the linked machine of the current db

Db.getMongo ()

Collection aggregate set

1. Create an aggregate collection (table)

Db.createCollection ("collName", {size: 20, capped: 5, max: 100})

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 ()

User-related

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")

Other

1. Query the previous error message

Db.getPrevError ()

2. Clear the error record

Db.resetError ()

View basic information about aggregate collections

1. View the help db.yourColl.help ()

2. Query the number of data items in the current collection db.yourColl.count ()

3. View the data space size db.userInfo.dataSize ()

4. Get the db db.userInfo.getDB () where the current aggregate set resides

5. Get the current aggregation status db.userInfo.stats ()

6. Get the total aggregate size db.userInfo.totalSize ()

7. Aggregate set storage space db.userInfo.storageSize ()

8. Shard version information db.userInfo.getShardVersion ()

9. Rename the aggregate collection db.userInfo.renameCollection ("users"); rename userInfo to users

10. Delete the current aggregate collection db.userInfo.drop ()

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 ({* *: {$exists: true}}) .count ()

Equivalent to: select count (* *) from userInfo

Indexes

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 ()

Modify, add, delete collection data

1. Add

Db.users.save ({name: 'zhangsan', age: 25, * *: 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.

Parameters.

Detailed explanation

Default value

Query

Query filter condition

{}

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

{}

Remove

If true, the selected object will be deleted before being returned

N/A

Update

A modifier object

N/A

New

If true, the modified object is returned instead of the original object. This parameter is ignored during the delete operation.

False

Fields

See Retrieving a Subset of Fields (1.5.0 +)

All fields

Upsert

Create a new object if the query result is empty. Example (1.5.4+)

False

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; i++) { ... db.users.save({name: "u_" + i, age: 22 + i, ***: i % 2}); ... }; 这样就循环添加了30条数据,同样也可以省略括号的写法 >

For (var I = 0; I

< 30; i++) db.users.save({name: "u_" + i, age: 22 + i, ***: i % 2}); 也是可以的,当你用db.users.find()查询的时候,显示多条数据而无法一页显示的情况下,可以用it查看下一页的信息; 4、find 游标查询 >

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; i++) printjson(c[i]); 7、将find游标转换成数组 >

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.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report