MongoDB database command operations

Source: Internet
Author: User
Tags install mongodb tojson

In the previous section, we have explained some understanding and concepts of MongoDB, so we will step into MongoDB learning.

Unlike apsaradb for MongoDB, which has powerful GUI clients, apsaradb for MongoDB also has powerful functions and stability, therefore, most operations on MongoDB are performed using commands similar to cmd commands (called shell operations in MongoDB). Therefore, learning MongoDB shell operations is an important foundation.

I. Preparations

1. Download MongoDB

: Http://www.mongodb.org/downloads

Select the appropriate version

Related documents: http://www.mongodb.org/display/DOCS/Tutorial

2. Install MongoDB

A. Pressure-free mode:

Open the downloaded mongodb-xxx.zip file, find the bindirectory, and run mongod.exe to start the service. The default port is 27017, And the DB is saved to the/data/DB directory of the root directory of the system C hard drive directory. Also, if your mongodb-xxx.zip file is on the E drive, you need to create a data/DB directory under drive C. MongoDB will not create this directory for you.

Then run Mongo to connect to the test database, and you can perform data operations. Run help to display the HELP command line.

B. Decompression Mode

Decompress the downloaded mongodb-xxx.zip file to any directory, find the bindirectory, and run mongod.exe to start MongoDB. The default port is port 27017, And the DB is saved in the/data/DB directory of the root directory of the hard disk directory where the ZIP file is located. Also, if your mongodb-xxx.zip file is on an elastic drive, you need to create a data/DB directory under the elastic drive. MongoDB will not create this directory for you.

Then run Mongo to connect to the test database, and you can perform data operations. Run help to display the HELP command line.

3. Simple Test

> 2 + 46> dbtest> // The database Fri May 20 16:47:39 malformed UTF-8 Character Sequence at offset 27error2 (shellhelp1) exec failed will be created when data is inserted for the first time: malformed UTF-8 Character Sequence at offset 27> dB. foo. insert ({ID: 2011, Username: 'hoojo ', age: 24, email: "hoojo_@126.com"});> dB. foo. find () ;{" _ id ": objectid (" 4dd62b0352a70cbe79e04f81 ")," ID ": 2011," username ":" hoojo "," Age ": 24, "email": "hoojo_@126.com"}>

The preceding simple operations show the currently used database, and add and query data.

Ii. Database shell Data Operations

The shell command operation syntax is similar to that of JavaScript. In fact, the underlying query statements on the console are all completed using JavaScript scripts.

Ø Database

1. Help to view command prompts

> help> db.help();> db.yourColl.help();> db.youColl.find().help();> rs.help();

2. Switch to/create a database

> use yourDB;

When a table is created, the current database is automatically created.

3. query all databases

> show dbs;

4. Delete the currently used database

> db.dropDatabase();

5. clone a database from a specified host

> db.cloneDatabase(“127.0.0.1”);

Clone the database data 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 mydb data of the local machine to the temp database.

7. Fix the current database

> db.repairDatabase();

8. view the currently used database

> db.getName();> db;

The dB and getname methods have the same effect. You can query the currently used database.

9. display the current dB status

> db.stats();

10. Current DB version

> db.version();

11. view the address of the linked machine of the current DB

> db.getMongo();

Collection aggregation set

1. Create an aggregation set (table)

> db.createCollection(“collName”, {size: 20, capped: 5, max: 100});

2. Get the clustering set (table) with the specified name)

> db.getCollection("account");

3. obtain all the aggregation sets of the current dB.

> db.getCollectionNames();

4. display the status of all clustered indexes of the current DB

> db.printCollectionStats();

User-related

1. Add a user

> db.addUser("name");> db.addUser("userName", "pwd123", true);

Add a user, set a password, and check whether the user is read-only

2. database authentication and security mode

> db.auth("userName", "123123");

3. display all current users

> show users;

4. delete a user

> db.removeUser("userName");

Other

1. query previous error messages

> db.getPrevError();

2. Clear error records

> db.resetError(); 
3. Collection collection operation

View the basic information of the aggregation set

1. View help

> db.yourColl.help();

2. query the number of data entries in the current set

> db.yourColl.count();

3. view the data space size

> db.userInfo.dataSize();

4. Obtain the dB of the current collection.

> db.userInfo.getDB();

5. Get the current cluster status

> db.userInfo.stats();

6. Get the total size of the aggregation set.

> db.userInfo.totalSize();

7. Size of the storage space of the aggregation set

> db.userInfo.storageSize();

8. Shard version information

> db.userInfo.getShardVersion()

9. Rename the clustering set

> db.userInfo.renameCollection("users");

Rename userinfo to users

10. Delete the current 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 on each page. If no record is displayed, you can use the IT iteration command to query data on the next page. Note: The it command cannot contain ";"

However, you can set the size of data displayed on each page. Use dbquery. shellbatchsize = 50 to display 50 records on each page.

2. query duplicate data of a column in the current clustering set after Removal

> db.userInfo.distinct("name");

The same data in name is filtered out.

Equivalent to: Select distict name from userinfo;

3. query records with age = 22

> db.userInfo.find({"age": 22});

Equivalent to: Select * From userinfo where age = 22;

4. query records of age> 22

> db.userInfo.find({age: {$gt: 22}});

Equivalent to: Select * From userinfo where age> 22;

5. query records of age <22

> db.userInfo.find({age: {$lt: 22}});

Equivalent to: Select * From userinfo where age <22;

6. query records with age> = 25

> db.userInfo.find({age: {$gte: 25}});

Equivalent to: Select * From userinfo where age> = 25;

7. query records of age <= 25

> db.userInfo.find({age: {$lte: 25}});

8. query age> = 23 and age <= 26

> db.userInfo.find({age: {$gte: 23, $lte: 26}});

9. query data whose name contains Mongo

> db.userInfo.find({name: /mongo/});

Equivalent to: Select * From userinfo where name like '% Mongo % ';

10. query names starting with Mongo

> db.userInfo.find({name: /^mongo/});

Select * From userinfo where name like 'mongo % ';

11. query the name and age data of a specified Column

> db.userInfo.find({}, {name: 1, age: 1});

Equivalent to: Select name, age from userinfo;

Of course, "true" or "false" can be used for name. If "true" is used, "river name: 1" has the same effect. If "false" is used, "name" is excluded and column information other than "name" is displayed.

12. query the name and age data of a specified column. 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 data with name = zhangsan and age = 22

> db.userInfo.find({name: 'zhangsan', age: 22});

Equivalent to: Select * From userinfo where name = 'hangsan' and age = '22 ';

15. query the first five data entries

> db.userInfo.find().limit(5);

Equivalent to: Select top 5 * From userinfo;

16. Query 10 data records later

> db.userInfo.find().skip(10);

Equivalent to: Select * From userinfo where id not in (select top 10 * From userinfo );

17. query data between 5-10

> db.userInfo.find().limit(10).skip(5);

It can be used for paging. limit is pagesize, and skip is the page * 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 data entry.

> db.userInfo.findOne();

Equivalent to: Select top 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 Column

> db.userInfo.find({sex: {$exists: true}}).count();

Equivalent to: Select count (sex) from userinfo;

Ø Index

1. Create an index

> db.userInfo.ensureIndex({name: 1});> db.userInfo.ensureIndex({name: 1, ts: -1});

2. query all indexes of the current clustered set

> db.userInfo.getIndexes();

3. view the total index record size

> db.userInfo.totalIndexSize();

4. Read all index information of the current set

> db.users.reIndex();

5. delete a specified index

> db.users.dropIndex("name_1");

6. Delete All indexes

> db.users.dropIndexes();

Modify, add, and delete collection data

1. Add

> db.users.save({name: ‘zhangsan’, age: 25, sex: true});

The data column of the added data is not fixed. The data column is subject to the added data.

2. Modify

> 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 = 'hohoho' where name = 'lisi ';

3. Delete

> db.users.remove({age: 132});

4. query, modify, and delete

> 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... });

Update or remove is a required parameter. Other parameters are optional.

Parameters

Details

Default Value

Query

Query filter conditions

{}

Sort

If multiple documents meet the query filtering conditions, the first object is selected based on the arrangement specified by this parameter.

{}

Remove

If it is true, the selected object will be deleted before return.

N/

Update

A modifier object

N/

New

If it is 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

If the query result of the created object is null.
Example (1.5.4 +)

False

1. Simple Hello World

> print("Hello World!");

This method calls the print function and directly writes "Hello world! "The effect is the same;

2. convert an object to JSON

> tojson(new Object());> tojson(new Object('a'));

3. Add data cyclically

> for (var i = 0; i < 30; i++) {... db.users.save({name: "u_" + i, age: 22 + i, sex: i % 2});... };

In this way, 30 pieces of data are added cyclically, and the brackets can also be omitted.

> for (var i = 0; i < 30; i++) db.users.save({name: "u_" + i, age: 22 + i, sex: i % 2});

You can also use it to view information on the next page when you use dB. Users. Find () to query multiple data entries and cannot display one page;

4. Find cursor Query

>var cursor = db.users.find();> while (cursor.hasNext()) { ... printjson(cursor.next()); ... }

In this way, all users information can be queried.

>var cursor = db.users.find();>while (cursor.hasNext()) { printjson(cursor.next); }

You can also omit the {} number.

5. foreach iteration Loop

>db.users.find().forEach(printjson);

In foreach, a function must be passed to process the data information of each iteration.

6. process the find cursor as an array

> var cursor = db.users.find();> cursor[4];

Obtain the data with the subscript index 4.

Since it can be processed as an array, We can get its length: cursor. Length (); or cursor. Count ();

In this way, we can also display data cyclically.

> for (var i = 0, len = c.length(); i < len; i++) printjson(c[i]);

7. Convert the find cursor to an array

> var arr = db.users.find().toArray();> printjson(arr[2]);

Convert toarray to an array

8. customize our own query results

Only show age <= 28 and only show age data

> db.users.find({age: {$lte: 28}}, {age: 1}).forEach(printjson);> db.users.find({age: {$lte: 28}}, {age: true}).forEach(printjson);

Exclude age Columns

> db.users.find({age: {$lte: 28}}, {age: false}).forEach(printjson);

9. foreach transfer function display information

> db.things.find({x:4}).forEach(function(x) {print(tojson(x));});

As mentioned above, foreach needs to pass a function. The function will accept a parameter, that is, the object of the current loop, and then process the input parameter information in the function weight.

 

So let's talk about MongoDB's shell operations first here, basically covering the most common MongoDB operation methods. The next section will show how to drive MongoDB using Java, crud.

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.