MongoDB often uses commands

Source: Internet
Author: User
Tags install mongodb mongodump mongorestore

First, we'll install the database. You can use Windows or Linux, but it is recommended to use Linux, I use ubuntu12.04. The URL below can be downloaded, basically a 64-bit system.

Assuming a bit Linux system can also be installed using the command line, I just use sudo apt-get install MongoDB.

Https://www.mongodb.org/downloads

MongoDB consists of databases, databases consists of collections, collections is composed of documents (equivalent to lines), and documents have field S (equivalent to columns).


Help

The first thing you should start with is the help function. The best documents for learning a thing are official documents. Below I will give a few instructions to run the process. The main form is db.help (), which can also be added to the middle of the database name, 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.getcol Lection (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 () Al  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.getsiblingd B (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.pr Intreplicationinfo () 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=slo W 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 F Ollowing 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 a object with these possible fields:name, unique, dropdupsdb.do Uban.reindex () Db.douban.find ([query],[fields])-query is an optional query filter.                                              Fields are 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 wit  H 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.to Talsize ()-Storage allocated for all data and indexesdb.douban.update (query, object[, Upsert_bool, Multi_bool]) Db.douban . Validate (<full>)-SLOWdb.douban.getShardVersion ()-only if use with shardingdb.douban.getShardDistribution () -Prints statistics about data distribution in the cluster


Use

Use Deng can be used to create Deng without worrying about Deng not being created, and when the first collection is created, Deng will create it on its own initiative.


Insert

Db.unicorns.insert ({name: ' demo ', Sex: ' M ', weight:70}), insert a data collection for unicorns. Using Db.getcollectionnames (), you get unicorns and system.indexes. System.indexes is available for each DB and is used to record index.

Ability to see if the insert succeeds through the Find function.


Find

Db.unicorns.find () will see document. is equivalent to the SELECT * from table in MySQL; View the entire contents of the collection.


Use Query        db.unicorns.find ({name: ' Dunx '}) Additional instructions:        $lt, $lte, $GT, $gte and $ne indicate less than, less than or equal to, greater than, greater than or equal to, Not equal to Db.unicorns.find ({gender: {$ne: ' F '}, Weight: {$gte: 701}}) $exists used to indicate whether the field exists 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})

Simply return the name of this field, as seen in detail below:

> Db.unicorns.find (null, {name:1}) {"_id": ObjectId ("4da6f22da8d5cd3b72081cf7"), "name": "Aurora"} {"_id": objecti D ("4da6f22da8d5cd3b72081cf6"), "name": "Horny"} {"_id": ObjectId ("4da6f22da8d5cd3b72081cf8"), "name": "Unicrom"} {"_i D ": ObjectId (" 4da6f22da8d5cd3b72081cf9 ")," name ":" Roooooodles "} {" _id ": ObjectId (" 4DA6F22DA8D5CD3B72081CFA ")," name " ":" Solnara "} {" _id ": ObjectId (" 4DA6F22DA8D5CD3B72081CFB ")," name ":" Ayna "} {" _id ": ObjectId (" 4da6f22da8d5cd3b72081c FC ")," name ":" Kenny "} {" _id ": ObjectId (" 4DA6F22DA8D5CD3B72081CFD ")," name ":" Raleigh "} {" _id ": ObjectId (" 4da6f22da8 D5cd3b72081cfe ")," name ":" Leia "} {" _id ": ObjectId (" 4DA6F22DA8D5CD3B72081CFF ")," name ":" Pilot "} {" _id ": ObjectId (" 4 Da6f22da8d5cd3b72081d00 ")," name ":" Nimue "} {" _id ": ObjectId (" 4da6f231a8d5cd3b72081d01 ")," name ":" Dunx "}> db.unic  Orns.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 means ascending,-1 means descending db.unicorns.find (). Sort ({weight:-1}). Limit (2). Skip (1) #得到第二个和第三个, limit specifies the number of queries, skip rules ignore a few.

Count
Db.unicorns.count ({vampires: {$gt:)} #ordb. Unicorns.find ({vampires: {$gt:)}). Count ()


Remove

Db.unicorns.remove () as seen below.

> Db.unicorns.remove () > Db.unicorns.find () >


Update

Db.unicorns.update ({name: ' Jingdong '}, {weight:590})

Note: After this statement is run, the full data of name ' Jingdong ' is queried first, and then the entire document with name ' Jingdong ' is replaced with {weight:590}.

That is Db.unicorns.insert ({name: ' Jingdong ', Dob:new Date (1979, 7,,), loves:[' Apple '), weight:575, Gender: ' m ', vamp IRES:99}); the whole is replaced with {weight:590}, and finally only one {weight:590}is left.



Running $set does not replace the original data, so the correct way to update it is as follows:

Db.unicorns.update ({name: ' Jingdong '}, {$set: {weight:590}})

Db.unicorns.update ({name: ' Pilot '}, {$inc: {<span style= "font-size:14px;" >WEIGHT:500</SPAN>}) $inc Add or decrease the number assuming that it turns 1000 after 500 because 500+500 = 1000db.unicorns.update ({name: ' Aurora '}, {$ Push: {loves: ' Sugar '}}) $push adding array elements $pop reducing array elements

If there is an update, add db.hits.update ({page: ' Unicorns '}, {$inc: {hits:1}}, True);d b.hits.find (), or True (upset) using the third parameter setting, default is False

#批量更新db. Unicorns.update ({}, {$set: {vaccinated:true}});d B.unicorns.find ({vaccinated:true}); All data will not be vaccinated is updated to true if all vaccinated of the data are updated to true, for example: Db.unicorns.update ({}, {$set: {vaccinated:true}}, False, True); Db.unicorns.find ({vaccinated:true});


Ensureindex

How indexes are created
Db.unicorns.ensureIndex ({name:1})
How to delete an index
Db.unicorns.dropIndex ({name:1})
Create a stand-alone index
Db.unicorns.ensureIndex ({name:1}, {unique:true})
Create a federated index
Db.unicorns.dropIndex ({name:1, Vampires:-1})


Using the web to get information about MongoDB

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


Data backup and Recovery

Backing up a database using Mongodump
Mongodump
Recovering a database using Mongorestore
Mongorestore











































MongoDB often uses commands

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.