MongoDB Common operations

Source: Internet
Author: User
Tags tojson

MongoDB use

After installing MongoDB, and starting MongoDB, basic operation:

Show DBS; Display database show collections; Displays the collection in the current database, similar to the table in MySQL database show users; Show user use <db name> switch the current database, as in MySQL

Database Common commands:

MongoDB does not have a command to create a database, but has a similar command, run the use <db name> command First, then do something like db.createcollection (' user ') so that you can create a database. Delete the database currently in use: Db.dropdatabase (); clone the database from the specified host: db.clonedatabase (' hostname/ip '); Copy the specified database from the specified machine to a database db.copydatabase (' mydb ', ' temp ', ' 127.0.0.1:27017 ') fix the current database: Db.repairdatabase (); View the database currently in use: Db.getname ()/DB display current DB status Db.stats () Current DB version db.version () View the address of the current DB link Machine Db.getmongo ()

Collection Collection Common commands:

Create a collection:  db.createcollection (' name ', {capped:<boolean>,autoindexid:<boolean>,size:< Number>,max:<number>})     name: Is the name of the collection,    capped:  Whether to enable the collection limit, if you need to set a constraint, the default is not enabled, this parameter does not make sense     size: limit the size of the collection to use space, default No Limit      max: The maximum number of bars in the collection is limited, the default is that there is no limit     autoIndexId:  whether to use ID as an index, and (True/false)      size  has a higher priority than max, such as:     1, db.createcollection (' log ')   No size, quantity limit, use _ ID as the default index &NBSP;&NBSP;&NBSP;&NBSP;2, limit the size of the collection space: db.createcollection (' log ', {size:1024})   or db.createcollection (' Log ', {capped:true,size:1024}), which limits the size of 1M and, if it exceeds 1M, deletes the oldest record     3, limiting the maximum number of bars in the collection:  Db.createcollection (' log ', {max:1024}), create a name for the log collection, the maximum number of bars is 1024, more than will delete the oldest record, this can not use Capped:true, otherwise will error      4, limit the maximum number of bars to use the space size, db.createcollection (' log ', {size:1024,max:1024}) or  db.createcollection (' log ', {capped:true,size:1024,max:1024})   LimitSystem set maximum usage space is 1M, the maximum number of bars is 1024      get the specified name of the collection  db.getcollection (' one ') to get all the current DB collection   Db.getcollectionnames () Displays the status of all collection indexes for the current DB  db.printcollectionstats ()

User Related actions:

MongoDB User and Authentication permissions summary: When the MongoDB service is newly installed MongoDB, when no parameters are added, the default is no permission authentication, the logged-on user can manipulate the database arbitrarily and can access the database remotely. At this point, MongoDB has an admin database by default and is empty, without logging permission-related information. When a user does not have a admin.system.users, even if MongoDB is started with the--auth parameter added, if the user is not added to the admin database, no authentication can be done at this time. Until a user is added to the admin.system.users. It is important to note that Admin.system.users will save user information that is larger than the user rights set in other databases, with super privileges, that is, users created in admin can manipulate other database data in MongoDB. 1, the MongoDB system, the database is created by the Superuser, a database can contain multiple users, a user can only be in a database, different database users may have the same name! 2, when admin.system.users a user does not have, even if mongod to add the--auth parameters, if the user is not added to the admin database, at this time no authentication or can do any action (whether or not to start with the--auth parameter), Until a user has been added to the admin.system.users. 3, the specific database, such as DB1 under the user User1, can not access other database DB2, but access to other user-created data in this database! 4. Users with the same name in different databases cannot log in to other databases! For example, Db1,db2 have user1, to user1 login DB1, can not log in to DB2 for database operation! 5, the user created in the Admin database has super privileges, you can manipulate the data objects of any database in the MONGODB system!

User-related command actions:

Add a User: Db.adduser (' name ') or Db.adduser (' username ', ' passwd123 ', true) add user, set password, read-only, default to False database authentication, Safe Mode Db.auth (' Username ', ' passwd ') shows all current users: Show users; Delete User: Db.removeuser (' username ')

Collection query:

Query all records: Db.userInfo.find ()   equivalent:select * from userinfo; The default is 20 records per page, when not displayed, you can use the IT iteration command to query the next page, Do not add after it, you can set the size of each page display data, with dbquery.shellbatchsize= 50; so that each page shows 50 records of the query to remove a column in the collection of duplicate data db.userInfo.distinct (' name '    equivalent to:select distict name from userinfo; query age=xx record db.userInfo.find ({' Age ': 22}) Query age>22 Records: Db.userInfo.find ({age:{$gt: $})    equivalent to:select * from userinfo  where age >22; query age<22 Records: Db.userInfo.find ({age:{$lt: 22}}) query age >=  25 of Records Db.userInfo.find ({age:{$gte: 25}) query age <= 25 for records db.userInfo.find ({age:{$lte: 25}) Query age  >= 23   age <= 26db.userinfo.find ({age:{$gte: $, $lte: 26}}) Query name contains MONGO data Db.userInfo.find ({name: /mongo/})   equivalent to:select * from userinfo  where name like  '%mongo% '; query name Db.userInfo.find ({name:/^mongo/}) starting with MONGO   equivalent: SELECT  * from userinfo where name like  ' mongo% '; query the specified column name,age data: Db.userInfo.find ({},{name:1,age:1})   equivalent: Select name, age  from userInfo; of course name can also be true or False when used with true, as in the case of an example effect, if False to exclude name, display information for columns other than name. Query the specified column name, age data,  age > 25db.userinfo.find ({age:{$gt: 25}},{name:1,age:1}) Query name =  Zhangsan, age = 22 data Db.userInfo.find ({name: ' Zhangsan ', age:22}) queries 10 data Db.userInfo.find (). Skip    equivalent to:select * from userinfo where id not in  ( selecttop 10 * from userinfo); query data between 5-10 Db.userInfo.find (). LIMT (). Skip (5) can be used for paging, Limit is Pagesize,skip is the first few pages *pagesizeand  query Db.userinfo ({' name ': ' Hurry ', ' age ': 18},{' name ': 1, ' Age ': 1})   Equivalent to: select name,age from userinfo  where name= ' hurry ' or with query Db.userInfo.find ({$or: &NBSP;[{AGE:22},{AGE:25}]})   equivalent: select * from userinfo where age = 22  or age = 25; using in,not in  ($in, $nin) db.userInfo.find ({' age ': {$in: [10,22,26]}})    equivalent: select * from users  where age in  (10, 22, 26); match with null db.userInfo.find ({' Age ': null}) Query the First Data: Db.userInfo.findOne ()   equivalent to:selecttop 1 * from userinfo; or: Db.userInfo.find (). Limit (1) query the number of record bars for a result set: Db.userInfo.find ({age:{$gte: +}}). Count ()   equivalent: Select count (*)  from  userinfo where age >= 25; sums by a column: Db.userInfo.find ({sex:{$exists: true}). Count ()   Equivalent to Select count (sex)  from userInfo;
Greater than, less than, greater than or equal to, less than or equal to $GT: greater than $lt: less than $gte: greater than or equal to $lte: less than or equal to not equal to: $ne modulo operation: $moddb. Userinfo.find ({' A ': {$mod: [10,1]}}) $all $all Similar to $in, but he needs to match all the values in the condition: such as an object: {a:[1,2,3]} This condition can match: Db.userInfo.find (a:{$all: [2,3]}) but this condition is not, Db.userInfo.find (a: {$all: [2,3,4]}) $size is the number of elements in the matching array, such as a pair of images: {a:[' foo '} This statement can be matched: Db.userInfo.find ({a:{$size: 1}) The official web said cannot be used to match a range of elements, if you want to find $size< 5 or something, they suggest creating a $exists$exists to determine if an element exists as follows: Db.userInfo.find ({a:{$exists: true}) returns Db.userInfo.find if A is present ({a:{$ Exists:false}) If no element A is present, return $not Db.userInfo.find ({' name ': {$not:/acme.*corp/i}}) $type $type match the type of an element based on the Bson type, Like matching by ID, Bson type and ID table:
Type description Type value

Double

1
String 2
Object 3
Array 4
Binary data 5

Object ID

7
Boolean 8
Date 9
Null 10
Regular expression 11

JavaScript Code

13
Symbol 14
JavaScript Code with scope 15
32-bit integer 16

Timestamp

17
64-bit integer 18

Min Key

255
Max Key 127

Use the following:

Db.userInfo.find ({a:{$type: 2}) if it is a string: string returns Adb.userInfo.find ({a:{$type: 16}) If it is of type int, return a

Regular expressions

MONGO supports regular expressions, such as Db.userInfo.find ({name:/acme.*corp/i}) after I means case-sensitive

Index:

CREATE INDEX: Db.userInfo.ensureIndex ({name:1}) Db.userInfo.ensureIndex ({name:1,ts:-1}) queries all indexes of the current collection: Db.userInfo.getIndexes () view total index record size db.userInfo.totalIndexSize () reads the current collection All index information Db.userInfo.reIndex () deletes the specified index: Db.userInfo.dropIndex ("name_ 1 ") Delete all Indexes db.userInfo.dropIndexes ()

Add to:

Db.userInfo.save ({' name ': ' Zhangsan ', ' Age ': 25,sex:true}) The data column of the added data, not fixed, according to the data added

Modify:

Db.userInfo.update ({age:25},{$set: {name: ' Lisi '}},false,true) corresponds to: Update users set name = ' ChangeName ' where age = 25; Db.userInfo.update ({name: ' Lisi '},{$inc: {age:50}},false,true) equals: Update users set age = Age + where name = ' Lisi ';d b.us Erinfo.update ({' name ': ' Lisi '},{$inc: {' age ': +}, $set: {name: ' HoHo '}},false,true)

Delete:

Db.userInfo.remove ({' Age ': 132})

Query modification Delete:

Db.userInfo.findAndModify ({query:{age:{$gte: 25}},sort:{age:-1},update:{$set: {name: ' A2 '}, $inc: {age:2}},remove: true}) Db.runcommand ({findandmodify: ' usersinfo ', query: {age:{$gte: 25}},sort: {age:-1},update:{$set: {name: ' A2 '},$ Inc:{age:2}},remove:true}) Update or remove one of them is a required parameter; Additional parameters are optional.

Sort:

Ascending: Db.userInfo.find (). Sort ({age:1}) Descending: Db.userInfo.find (). Sort ({age:-1})

Convert an object to JSON

Tojson (New Object ()) Tojson (New Ojbect (' a '))

Loop to add data:

> for (var i = 0; i < i++) {Db.userInfo.save ({name: ' u_ ' + i, age:22 + i,sex:i% 2})} This adds 30 data to the loop, and can also omit the notation of parentheses &G T for (var i = 0; i < i++) {Db.userInfo.save ({name: ' u_ ' +i,age:22+i,sex:i%2})}

Find cursor Query

> var cursor = db.userInfo.find () > while (Cursor.hasnext ()) {Printjson (Cursor.next ())} This will query all the users information, The same can be said of var cursor = Db.users.find (); while (Cursor.hasnext ()) {Printjson (Cursor.next)}

foreach Iteration Loops

Db.users.find (). foreach (Printjson) foreach must pass a function to handle the data information for each iteration

The find cursor is treated as an array

var cursor = Db.users.find () cursor[4] The data with the subscript index of 4 can be processed as an array, so it can be obtained in length: Cursor.length (); or cursor.count (); That way we can also display the data for (var i = 0, Len = c.length (); i < Len; i++) Printjson (C[i]) to convert the find cursor to an array >var arr = Db.userInfo.find (). ToArray () >printjson (arr[2]) convert it to an array using the ToArray method

Other:

Error message before query: Db.getpreverror (); Clear Error Record: Db.reseterror ()


This article from the "Linux Learning" blog, reproduced please contact the author!

MongoDB Common operations

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.