MongoDB syntax usage Summary

Source: Internet
Author: User
Tags findone

The supported data structure is very loose and is similar to the json bjson format. Therefore, it can store complicated data types. The biggest feature of Mongo is that it supports a very powerful query language. Its syntax is somewhat similar to an Object-Oriented Query Language. It can almost implement most of the functions similar to single-table queries in relational databases, it also supports data indexing.
It features high performance, ease of deployment, and ease of use, making it easy to store data.

1. MongoDB acquisition and installation

(1) Get the address http://www.mongodb.org/downloads according to their needs to select the corresponding version, linux can use wget command.
(2) unzip the mongodb-win32-i386-1.8.1
(3) create a data storage folder. The default data directory/data/db of mongodb
C:/> mkdir/data
C:/> mkdir/data/db
(4) Run MongoDB
Mongod.exe-database server, equivalent to mysql mysqld command, start the server
Cmd.exe-database client, which is equivalent to mysql Command. Open the management console.

Start the service
Mongod.exe -- dbpath F:/DataBase/MongoDB/db/
-- Dbpath: data file storage path
-- Port Data Service port
C:/> cd/my_1__dir/bin
C:/my_cmd_dir/bin> mongod // start the mongod server. Default database path/data/db, port 27071
Start the client
Cmd.exe cclove
Name of the database connected to cclove
C:/> cd/my_1__dir/bin
C:/my_1__dir/bin> mongo

2. Familiar with MongoDB data operation statements, such as SQL

Database Operation syntax
Mongo -- path
Db. AddUser (username, password) Add User
Db. auth (usrename, password) sets database connection Verification
Db. cloneDataBase (fromhost) clone a database from the target server
Db. commandHelp (name) returns the help for the command
Db. copyDatabase (fromdb, todb, fromhost) copy the database fromdb --- source database name, todb --- target database name, fromhost --- source database server address
Db. createCollection (name, {size: 3333, capped: 333, max: 88888}) to create a dataset, equivalent to a table
Db. currentOp () cancels the current operation of the current database
Db. dropDataBase () Delete the current database
Db. eval (func, args) run code server-side
Db. getCollection (cname) obtains a data set. The same usage is db ['cname'] or db. cname.
Db. getCollenctionNames () Get the name list of all data sets
Db. getLastError () returns the message indicating the last error.
Db. getLastErrorObj () returns the last error object
Db. getMongo () gets the connection object of the current server get the server connection object
Db. getMondo (). setSlaveOk () allow this connection to read from then nonmaster membr of a replica pair
Db. getName () returns the name of the database to be operated on.
Db. getPrevError () returns the previous error object
Db. getProfilingLevel ()? Level
Db. getReplicationInfo ()? What information
Db. getSisterDB (name) get the db at the same server as this onew
Db. killOp () Stop (kill) the current operation in the current database
Db. printCollectionStats () returns the dataset status of the current database
Db. printReplicationInfo ()
Db. printSlaveReplicationInfo ()
Db. printShardingStatus () returns whether the current database is a shared database
Db. removeUser (username) delete a user
Db. repairDatabase () repairs the current database
Db. resetError ()
Db. runCommand (cmdObj) run a database command. if cmdObj is a string, turns it into {cmdObj: 1}
Db. setProfilingLevel (level) 0 = off, 1 = slow, 2 = all
Db. shutdownServer () Close the current service program
Db. version () returns the version information of the current program.

Dataset (table) operation syntax
Db. linlin. find ({id: 10}) returns the linlin dataset ID = 10
Db. linlin. find ({id: 10}). count () returns the total number of data records with linlin dataset ID = 10.
Db. linlin. find ({id: 10}). limit (2) returns the dataset whose linlin dataset ID = 10 starts from the second one.
Db. linlin. find ({id: 10}). skip (8) returns the data set of the linlin dataset ID = 10 from 0 to the eighth.
Db. linlin. find ({id: 10}). limit (2). skip (8) returns the data of the linlin dataset ID = 1 = from the second to the eighth.
Db. linlin. find ({id: 10}). sort () returns the sorted dataset with the linlin dataset ID = 10.
Db. linlin. findOne ([query]) returns a data record that meets the condition.
Db. linlin. getDB () returns the name of the database to which the dataset belongs.
Db. linlin. getIndexes () returns index information for some datasets.
Db. linlin. group ({key:..., initial:..., reduce:... [, cond:...]})
Db. linlin. mapReduce (mayFunction, performancefunction, <optional params>)
Db. linlin. remove (query) deletes a piece of data in the dataset.
Db. linlin. renameCollection (newName) rename some dataset names
Db. linlin. save (obj) inserts a data entry into the dataset.
Db. linlin. stats () returns the status of this dataset
Db. linlin. storageSize () returns the storage size of this dataset.
Db. linlin. totalIndexSize () returns the size of the index file for this dataset.
Db. linlin. totalSize () returns the total size of some datasets.
Db. linlin. update (query, object [, upsert_bool]) updates a piece of data in this dataset.
Db. linlin. validate () verifies this dataset
Db. linlin. getShardVersion () returns the shared version of the dataset.

Db. linlin. find ({'name': 'foobar'}) select * from linlin where name = 'foobar'
Db. linlin. find () select * from linlin
Db. linlin. find ({'id': 10}). count () select count (*) from linlin where ID = 10
Db. linlin. find (). skip (10). limit (20) reads 20 data records starting from the tenth query result select * from linlin limit ---------- mysql
Db. linlin. find ({'id': {$ in: [, 45]}) select * from linlin where ID in (, 45)
Db. linlin. find (). sort ({'id':-1}) select * from linlin order by ID desc
Db. linlin. distinct ('name', {'id': {$ lt: 20}) select distinct (name) from linlin where ID <20

Db. linlin. group ({key: {'name': true}, cond: {'name': 'foo'}, reduce: function (obj, prev) {prev. msum + = obj. marks;}, initial: {msum: 0 }})
Select name, sum (marks) from linlin group by name
Db. linlin. find ('this. ID <20', {name: 1}) select name from linlin where ID <20

Db. linlin. insert ({'name': 'foobar', 'age': 25}) insert into linlin ('name', 'age') values ('foobar', 25)
Db. linlin. insert ({'name': 'foobar', 'age': 25, 'email ': 'cclove2 @ 163.com '})

Db. linlin. remove ({}) delete * from linlin
Db. linlin. remove ({'age': 20}) delete linlin where age = 20
Db. linlin. remove ({'age': {$ lt: 20 }}) delete linlin where age <20
Db. linlin. remove ({'age': {$ lte: 20}) delete linlin where age <= 20
Db. linlin. remove ({'age': {$ gt: 20}) delete linlin where age> 20
Db. linlin. remove ({'age': {$ gte: 20}) delete linlin where age> = 20
Db. linlin. remove ({'age': {$ ne: 20}) delete linlin where age! = 20

Db. linlin. update ({'name': 'foobar'}, {$ set: {'age': 36}) update linlin set age = 36 where name = 'foobar'
Db. linlin. update ({'name': 'foobar'}, {$ inc: {'age': 3 }}) update linlin set age = age + 3 where name = 'foobar'

Table of Operation statements officially provided:

Upstream: SQL statement
Downstream: Mongo operation statement
Create table users (a Number, B Number)
Db. createCollection ("mycoll ")

Insert into users values (1, 1)
Db. users. insert ({a: 1, B: 1 })

SELECT a, B FROM users
Db. users. find ({}, {a: 1, B: 1 })

SELECT * FROM users
Db. users. find ()

SELECT * FROM users WHERE age = 33
Db. users. find ({age: 33 })

SELECT a, B FROM users WHERE age = 33
Db. users. find ({age: 33}, {a: 1, B: 1 })

SELECT * FROM users WHERE age = 33 order by name
Db. users. find ({age: 33}). sort ({name: 1 })

SELECT * FROM users WHERE age> 33
Db. users. find ({'age': {$ gt: 33 }})})

SELECT * FROM users WHERE age <33
Db. users. find ({'age': {$ lt: 33 }})})

SELECT * FROM users WHERE name LIKE "% Joe %"
Db. users. find ({name:/Joe /})

SELECT * FROM users WHERE name LIKE "Joe %"
Db. users. find ({name:/^ Joe /})

SELECT * FROM users WHERE age> 33 AND age <= 40
Db. users. find ({'age': {$ gt: 33, $ lte: 40 }})})

SELECT * FROM users order by name DESC
Db. users. find (). sort ({name:-1 })

SELECT * FROM users WHERE a = 1 and B = 'Q'
Db. users. find ({a: 1, B: 'q '})

SELECT * FROM users LIMIT 10 SKIP 20
Db. users. find (). limit (10). skip (20)

SELECT * FROM users WHERE a = 1 or B = 2
Db. users. find ({$ or: [{a: 1 },{ B: 2}]})

SELECT * FROM users LIMIT 1
Db. users. findOne ()

Select distinct last_name FROM users
Db. users. distinct ('Last _ name ')

Select count (* y) FROM users
Db. users. count ()

Select count (* y) FROM users where AGE> 30
Db. users. find ({age: {'$ gt': 30}). count ()

Select count (AGE) from users
Db. users. find ({age: {'$ exists': true}). count ()

Create index myindexname ON users (name)
Db. users. ensureIndex ({name: 1 })

Create index myindexname ON users (name, ts DESC)
Db. users. ensureIndex ({name: 1, ts:-1 })

Explain select * FROM users WHERE z = 3
Db. users. find ({z: 3}). explain ()

UPDATE users SET a = 1 WHERE B = 'Q'
Db. users. update ({B: 'q'}, {$ set: {a: 1 }}, false, true)

UPDATE users SET a = a + 2 WHERE B = 'Q'
Db. users. update ({B: 'q'}, {$ inc: {a: 2 }}, false, true)

Delete from users WHERE z = "abc"
Db. users. remove ({z: 'abc '});

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.