Common commands of MongoDB

Source: Internet
Author: User
Tags install mongodb mongodump mongorestore

Common commands of MongoDB

First, install the database. You can use windows or linux, but linux is recommended. I use ubuntu12.04. you can download the database at the following URL, it is usually a 64-bit system. If you use a linux system, you can use the command line to install mongodb. I just use sudo apt-get install mongodb.

https://www.mongodb.org/downloads

MongoDB is composed of databases, databases is composed of collections, collections is composed of documents (equivalent to rows), and documents are composed of fields (equivalent to columns.


Help

The help function should be introduced at the beginning. The best document for learning something is the official document. Below I will provide several instructions for execution. The most basic form is db. help (). You can also add the database name in the middle, such as db. douban. help ().

> db.help()DB methods:db.addUser(username, password[, readOnly=false])db.auth(username, password)db.cloneDatabase(fromhost)db.commandHelp(name) returns the help for the commanddb.copyDatabase(fromdb, todb, fromhost)db.createCollection(name, { size : ..., capped : ..., max : ... } )db.currentOp() displays the current operation in the dbdb.dropDatabase()db.eval(func, args) run code server-sidedb.getCollection(cname) same as db['cname'] or db.cnamedb.getCollectionNames()db.getLastError() - just returns the err msg stringdb.getLastErrorObj() - return full status objectdb.getMongo() get the server connection objectdb.getMongo().setSlaveOk() allow this connection to read from the nonmaster member of a replica pairdb.getName()db.getPrevError()db.getProfilingLevel() - deprecateddb.getProfilingStatus() - returns if profiling is on and slow threshold db.getReplicationInfo()db.getSiblingDB(name) get the db at the same server as this onedb.isMaster() check replica primary statusdb.killOp(opid) kills the current operation in the dbdb.listCommands() lists all the db commandsdb.logout()db.printCollectionStats()db.printReplicationInfo()db.printSlaveReplicationInfo()db.printShardingStatus()db.removeUser(username)db.repairDatabase()db.resetError()db.runCommand(cmdObj) run a database command.  if cmdObj is a string, turns it into { cmdObj : 1 }db.serverStatus()db.setProfilingLevel(level,<slowms>) 0=off 1=slow 2=alldb.shutdownServer()db.stats()db.version() current version of the serverdb.getMongo().setSlaveOk() allow queries on a replication slave serverdb.fsyncLock() flush data to disk and lock server for backupsdb.fsyncUnock() unlocks server following a db.fsyncLock()

> db.douban.help()DBCollection helpdb.douban.find().help() - show DBCursor helpdb.douban.count()db.douban.dataSize()db.douban.distinct( key ) - eg. db.douban.distinct( 'x' )db.douban.drop() drop the collectiondb.douban.dropIndex(name)db.douban.dropIndexes()db.douban.ensureIndex(keypattern[,options]) - options is an object with these possible fields: name, unique, dropDupsdb.douban.reIndex()db.douban.find([query],[fields]) - query is an optional query filter. fields is optional set of fields to return.                                              e.g. db.douban.find( {x:77} , {name:1, x:1} )db.douban.find(...).count()db.douban.find(...).limit(n)db.douban.find(...).skip(n)db.douban.find(...).sort(...)db.douban.findOne([query])db.douban.findAndModify( { update : ... , remove : bool [, query: {}, sort: {}, 'new': false] } )db.douban.getDB() get DB object associated with collectiondb.douban.getIndexes()db.douban.group( { key : ..., initial: ..., reduce : ...[, cond: ...] } )db.douban.mapReduce( mapFunction , reduceFunction , <optional params> )db.douban.remove(query)db.douban.renameCollection( newName , <dropTarget> ) renames the collection.db.douban.runCommand( name , <options> ) runs a db command with the given name where the first param is the collection namedb.douban.save(obj)db.douban.stats()db.douban.storageSize() - includes free space allocated to this collectiondb.douban.totalIndexSize() - size in bytes of all the indexesdb.douban.totalSize() - storage allocated for all data and indexesdb.douban.update(query, object[, upsert_bool, multi_bool])db.douban.validate( <full> ) - SLOWdb.douban.getShardVersion() - only for use with shardingdb.douban.getShardDistribution() - prints statistics about data distribution in the cluster


Use

Use deng can be used to create deng, so you do not have to worry that deng will not be created. When you create the first collection, deng will automatically create it.


Insert

Db. unicorns. insert ({name: 'Demo', sex: 'M', weight: 70}), insert a data collection as unicorns, and use db. getCollectionNames () will get unicorns and system. indexes. System. indexes is available for each database and used to record the index. You can use the find function to check whether the insert operation is successful.


Find

Db. unicorns. find () will see the document. It is equivalent to select * from table; in mysql to view all content in the set.


Use query db. unicorns. find ({name: 'dunx'}) other instructions: $ lt, $ lte, $ gt, $ gte and $ ne respectively indicate less than, less than or equal to, greater than, greater than or equal to, and not equal to db. unicorns. find ({gender: {$ ne: 'F'}, weight: {$ gte: 701}) $ exists indicates whether the field has a db. unicorns. find ({vampires :{$ exists: false }}) or and anddb. unicorns. find ({gender: 'F', $ or: [{loves: 'apple'}, {loves: 'Orange '}, {weight: {$ lt: 500}]})


Db. unicorns. find (null, {name: 1 })

Only the field name is returned, as shown below:

> db.unicorns.find(null, {name: 1}){ "_id" : ObjectId("4da6f22da8d5cd3b72081cf7"), "name" : "Aurora" }{ "_id" : ObjectId("4da6f22da8d5cd3b72081cf6"), "name" : "Horny" }{ "_id" : ObjectId("4da6f22da8d5cd3b72081cf8"), "name" : "Unicrom" }{ "_id" : ObjectId("4da6f22da8d5cd3b72081cf9"), "name" : "Roooooodles" }{ "_id" : ObjectId("4da6f22da8d5cd3b72081cfa"), "name" : "Solnara" }{ "_id" : ObjectId("4da6f22da8d5cd3b72081cfb"), "name" : "Ayna" }{ "_id" : ObjectId("4da6f22da8d5cd3b72081cfc"), "name" : "Kenny" }{ "_id" : ObjectId("4da6f22da8d5cd3b72081cfd"), "name" : "Raleigh" }{ "_id" : ObjectId("4da6f22da8d5cd3b72081cfe"), "name" : "Leia" }{ "_id" : ObjectId("4da6f22da8d5cd3b72081cff"), "name" : "Pilot" }{ "_id" : ObjectId("4da6f22da8d5cd3b72081d00"), "name" : "Nimue" }{ "_id" : ObjectId("4da6f231a8d5cd3b72081d01"), "name" : "Dunx" }> db.unicorns.find(null, {name: 1,_id:0}){ "name" : "Aurora" }{ "name" : "Horny" }{ "name" : "Unicrom" }{ "name" : "Roooooodles" }{ "name" : "Solnara" }{ "name" : "Ayna" }{ "name" : "Kenny" }{ "name" : "Raleigh" }{ "name" : "Leia" }{ "name" : "Pilot" }{ "name" : "Nimue" }{ "name" : "Dunx" }

Sort

Db. unicorns. find (). sort ({weight:-1}) db. unicorns. find (). sort ({name: 1, vampires:-1}) #1 indicates ascending, and-1 indicates descending db. unicorns. find (). sort ({weight:-1 }). limit (2 ). skip (1) # obtain the second and third. The number of limit queries is specified, and the number of skip entries is ignored.

Count 
db.unicorns.count({vampires: {$gt: 50}})#ordb.unicorns.find({vampires: {$gt: 50}}).count()


Remove

Db. unicorns. remove () is shown below.> Db. unicorns. remove ()> db. unicorns. find ()>


Update

db.unicorns.update({name: 'jingdong'}, {weight: 590})

Note: After executing this statement, first query all data whose name is 'jingdong', and then replace the entire document whose name is 'jingdong' with {weight: 590 }.

Db. unicorns. insert ({name: 'jingdong', dob: new Date (1979, 7, 18, 18, 44), loves: ['apple'], weight: 575, gender: 'M', vampires: 99}); replace {weight: 590} with only one {weight: 590 }.

Run $ set without replacing the original data. Therefore, the correct update method is as follows:

db.unicorns.update({name: 'jingdong'}, {$set: {weight: 590}})

Db. unicorns. update ({name: 'pilo'}, {$ inc: {<span style = "font-size: 14px;"> weight: 500 </span> }}) $ inc increase or decrease the number. If it is 500, it will change to 1000, because 500 + 500 = 1000db. unicorns. update ({name: 'aurora '}, {$ push: {loves: 'sugal'}) $ push adds array elements $ pop to reduce array elements

If yes, update the database. Otherwise, add the database. hits. update ({page: 'unicorns'}, {$ inc: {hits: 1 }}, true); db. hits. find (); Use the third parameter to set whether to be true (upset). The default value is false.

# Batch update db. unicorns. update ({},{$ set: {vaccinated: true }}); db. unicorns. find ({vaccinated: true}); the vaccinated of all data is not updated to true. If the vaccinated of all data is updated to true, the db is as follows. unicorns. update ({},{ $ set: {vaccinated: true }}, false, true); db. unicorns. find ({vaccinated: true });


EnsureIndex

How to create an index
Db. unicorns. ensureIndex ({name: 1 })
How to delete an index
Db. unicorns. dropIndex ({name: 1 })
Create independent index
Db. unicorns. ensureIndex ({name: 1}, {unique: true })
Create a joint index
Db. unicorns. dropIndex ({name: 1, vampires:-1 })


Use the web to obtain mongoDB Information

Use http: // localhost: 28017/to obtain MongoDB information.


Data backup and recovery

Use mongodump to back up a database
Mongodump
Use mongorestore to restore a database
Mongorestore











































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.