Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

MongoDB basic commands are used

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)06/01 Report--

After starting MongoDB successfully, open a command line window and type mongo, and you can do some database operations.

Enter help to see the basic operation commands:

Show dbs: displaying a list of databases

Show collections: displays collections in the current database (similar to tables in a relational database)

Show users: displaying users

Use: switch the current database, which is the same as in MS-SQL

Db.help (): displays database operation commands, with many commands in it

Db.foo.help (): show collection operation commands. There are also many commands. Foo refers to a collection called foo under the current database, not a real command.

Db.foo.find (): performs a data lookup for the foo collection in the current database (all data is listed because there are no conditions)

Db.foo.find ({a: 1}): looks up the foo collection in the current database if there is an attribute in the data called an and the value of an is 1

MongoDB does not have a command to create a database, but there are similar commands.

For example, if you want to create a "myTest" database, first run the use myTest command, and then do some operations (such as: db.createCollection ('user')), so you can create a database called "myTest".

Database common commands

1. Help view command prompts

Help

Db.help ()

Db.yourColl.help ()

Db.youColl.find () .help ()

Rs.help ()

2. Switch / create database

Use yourDB; automatically creates the current database when you create a collection (table)

3. Query all databases

Show dbs

4. Delete the database currently in use

Db.dropDatabase ()

5. Clone the database from the specified host

Db.cloneDatabase ("127.0.0.1"); Clones the data from the database 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 local mydb data to the temp database

7. Repair the current database

Db.repairDatabase ()

8. View the database currently in use

Db.getName ()

The db; db and getName methods have the same effect, and both can query the currently used database.

9. Display the current db status

Db.stats ()

10. Current db version

Db.version ()

11. Check the address of the linked machine of the current db

Db.getMongo ()

Collection aggregate set

1. Create an aggregate collection (table)

Db.createCollection ("collName", {size: 20, capped: 5, max: 100})

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

Db.getCollection ("account")

3. Get all the aggregate sets of the current db

Db.getCollectionNames ()

4. Display the status of all clustered indexes in the current db

Db.printCollectionStats ()

User-related

1. Add a user

Db.addUser ("name")

Db.addUser ("userName", "pwd123", true); add user, set password, read-only or not

2. Database authentication and security mode

Db.auth ("userName", "123123")

3. Show all current users

Show users

4. Delete a user

Db.removeUser ("userName")

Other

1. Query the previous error message

Db.getPrevError ()

2. Clear the error record

Db.resetError ()

View basic information about aggregate collections

Db.yourColl.help (); db.yourColl.count (); db.userInfo.dataSize (); db.userInfo.getDB (); db.userInfo.stats (); db.userInfo.totalSize (); db.userInfo.storageSize (); db.userInfo.getShardVersion () db.userInfo.renameCollection ("users"); rename userInfo to users db.userInfo.drop ()

Aggregate collection query

1. Query all records

Db.userInfo.find (); equivalent to: select* from userInfo; displays 20 records per page by default. When the display is not down, you can use the it iterative command to query the next page of data. Note: you cannot type the it command with ";" but you can set the size of the data displayed per page, using DBQuery.shellBatchSize= 50; that will show 50 records per page.

2. After the query is removed, the duplicate data of a column in the current aggregate collection is removed.

Db.userInfo.distinct ("name"); will filter out the same data in name equivalent to: select distict name from userInfo

3. Query the records with age = 22

Db.userInfo.find ({"age": 22}); equivalent to: select * from userInfo where age = 22

4. Query the records with age > 22

Db.userInfo.find ({age: {$gt: 22}}); equivalent to: select * from userInfo where age > 22

5. Query age

< 22的记录 db.userInfo.find({age: {$lt: 22}});相当于:select * from userInfo where age = 25的记录 db.userInfo.find({age: {$gte: 25}});相当于:select * from userInfo where age >

= 25

7. Query age = 23 and 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: db.userInfo.find (). Sort ({age: 1}); descending: db.userInfo.find (). Sort ({age:-1})

14. Query the data of name = zhangsan, age = 22

Db.userInfo.find ({name: 'zhangsan', age: 22}); equivalent to: select * from userInfo where name =' zhangsan' and age = '22'

15. Query the first five pieces of data

Db.userInfo.find () .limit (5); equivalent to: selecttop 5 * from userInfo

16. Query the data after 10 items

Db.userInfo.find () .skip (10); equivalent to: select * from userInfo where id not in (selecttop 10 * from userInfo)

17. Query data between 5 and 10

Db.userInfo.find () .limit (10) .skip (5); can be used for paging, limit is the number of pages pageSize,skip is * 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 piece of data

Db.userInfo.findOne (); equivalent to: selecttop 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 a column

Db.userInfo.find ({sex: {$exists: true}}) .count (); equivalent to: select count (sex) from userInfo

Indexes

1. Create an index

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

2. Query all indexes of the current cluster

Db.userInfo.getIndexes ()

3. View the total index record size

Db.userInfo.totalIndexSize ()

4. Read all the index information of the current collection

Db.users.reIndex ()

5. Delete the specified index

Db.users.dropIndex ("name_1")

6. Delete all indexes

Db.users.dropIndexes ()

Modify, add, delete collection data

1. Add

Db.users.save ({name: 'zhangsan', age: 25, sex: true}); the data column of the added data, which is not fixed and based on the added data.

2. Modification

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 = 'hoho' where name =' Lisi'

3. Delete

Db.users.remove ({age: 132})

4. Query modification and deletion

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

Statement block operation

1. Simple Hello World

Print ("Hello World!"); this method calls the print function and writes "Hello World!" directly. The effect is the same.

2. Convert an object to json

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

3. Add data in a loop

> for (var I = 0; I

< 30; i++) {... db.users.save({name: "u_" + i, age: 22 + i, sex: i % 2});... };这样就循环添加了30条数据,同样也可以省略括号的写法>

For (var I = 0; I

< 30; i++) db.users.save({name: "u_" + i, age: 22 + i, sex: i % 2});也是可以的,当你用db.users.find()查询的时候,显示多条数据而无法一页显示的情况下,可以用it查看下一页的信息; 4、find 游标查询 >

Var cursor = db.users.find (); > while (cursor.hasNext ()) {printjson (cursor.next ());} this queries all users information, and you can also write var cursor = db.users.find (); while (cursor.hasNext ()) {printjson (cursor.next);} you can also omit the {} sign.

5. ForEach iterative cycle

Db.users.find (). ForEach (printjson); forEach must pass a function to process the data information for each iteration

6. Treat find cursors as arrays

Var cursor = db.users.find (); cursor [4]; since the data with subscript 4 can be treated as an array, its length can be obtained: cursor.length (); or cursor.count (); then we can also loop the data for (var I = 0, len = c.length (); I

< len; i++) printjson(c[i]); 7、将find游标转换成数组 >

Var arr = db.users.find () .toArray (); > printjson (arr [2]); convert it to an array using the toArray method

8. Customize our own query results

Show only age

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report