MongoDB common commands

Posted by danbot26 on Tue, 04 Jan 2022 21:32:14 +0100

1. Create database

use testdb

2. Create collection



3. Inquiry


4. Modification

db.t_member.update({name:"zhaomin"},{$set:{age:18}}) #Other attribute columns will not be affected, and errors will be reported if the primary key conflicts
db.t_member.update({name:"zhaomin"},{$set:{age:18}},true)#The third parameter is true Then execute insertOrUpdate Operation, update if found, insert if not found, or
var p = db.t_member.findOne();
db.t_member.update(p,{name:"zhaomin1"}) #Other attribute columns are deleted

5. Delete

db.t_member.remove({age:1}) #Delete the first item that meets the conditions. Only delete the data, not the index
#Delete collection
#Delete database

6. View collection

show collections

7. View database

show dbs

8. Insert data

db.t_member.insert() #Duplicate key values are not allowed #If the key value is repeated, it can be changed to insert operation

9. Batch update


The batch operation needs to be used together with the selector. The first false indicates that the insertOrUpdate operation is not executed, and the second true indicates that the batch operation is executed

10. Updater

$set: specify a key value pair. If it exists, it will be modified. If it does not exist, it will be added
$inc: only used for numeric types. You can add or subtract numeric types of specified key value pairs:


The result is that the age of "zhangsan" is increased by 2
$unset: deletes the specified key


$push: array key operation: 1. If there is a specified array, add a value for it; 2. If the specified array does not exist, create an array key and add a value; 3. If the specified key is not an array type, an error is reported;
$pushAll: batch array key insertion value


$addToSet: when there is this value in the specified array, it is not inserted; otherwise, it is inserted

db.t_member.update({name:"zhangsan"},{$addToSet:{classes:"English"}}); #Will not be added to the array

$pop: delete the value of the specified array. When value=1, delete the last value, and when value=-1, delete the first value

db.t_member.update({name:"zhangsan"},{$pop:{classes:1}}) #The last value was deleted

$pull: deletes the value specified in the specified array

db.persons.update({name:"zhangsan"},{$pull:{classes:"Chinese"}}) #$pullAll Batch delete specified array

#If there are more than one in the array Chinese,Delete all

$: when modifying the specified array, if the array has multiple objects, but you only want to modify some of them, you need a locator:


$addToSet is combined with $each to complete the batch array update operation


11. runCommand function and findAndModify function

  new:true Return modified data

The runCommand function executes special functions in mongdb
findAndModify is one of the special functions used to return the document after update or remove
For example:


12. System command example

1. Query server version number and host operating system


2. Query execution set details, size, space, index, etc


3. View the last error message of this operation set


13. Fixed set

1. Characteristics

Fixed sets have no index by default_ id also has no index. Because there is no need to allocate new space, its insertion speed is very fast, and the order of fixed sets is determined, resulting in very fast query speed. The most suitable is log management

2. Create fixed collection

Creating a new fixed collection requires a size of 100 bytes and can store 10 documents


Convert a normal set into a fixed set


3. Sort fixed sets in reverse. By default, the order of insertion is sorted


14. MongoDB advanced query


The first empty bracket indicates that all data will be queried. In the second bracket, a value of 0 indicates no return, and a value of 1 indicates return. By default, if no primary key is specified, the primary key will always be returned;

db.persons.find({condition},{Specify key});

Comparison operator: $LT: < $LTE: < = $GT: > $GTE: > = $ne:=

14.1 query criteria

#Query people aged 25 or older and 27 or younger 
db.t_member.find({country:{$ne:"the republic of korea"}},{_id:0,name:1,country:1}) 
#Find out the math scores of all people whose nationality is not South Korea 

14.2. Include and exclude (for arrays only)

$in or $nin

#Query the information of students whose nationality is China or the United States 

14.3, $or query

db.t_member.find({$or:[{c:{$gt:85}},{e:{$gt:90}}]},{_id:0,name:1,c:1,e:1}) #Query the information of students whose Chinese scores are greater than 85 or English scores are greater than 90
#Add new keys to students of Chinese nationality sex 
#Find out sex by null People 

14.4 regular expressions

#"Found in name" li"Student information

14.5 use of $not

The difference between $not and $nin is that $not can be used anywhere, $nin is used on sets

#"The name does not exist in the query" li"Student information

14.6 use of $all and index

#Query like to see MONGOD and JS Students
#The second book is JAVA Learning information

14.7 the use of $size cannot be used at the same time as the comparison query character

#Find out the students who like 4 books

14.8. Find out students who like more than 4 books

1. Add size key


2. Add books and update size


3. Query more than 3 copies


14.9. The $slice operator returns the internal value of the specified array in the document

#Find out Jim 2nd in bookshelf~4 This book
#Find out the last book

14.10 document query

Find out the students who have studied in K and got an A

1. Absolute query, the order and the number of keys should be completely consistent


2. Object mode, but errors will occur. Multiple conditions may query multiple objects


3. The correct approach is to query $elemMatch for a single condition group


14.11 paging and sorting

1. limit returns the specified number of items and queries the first 5 items of data in the persons document:


2. Specify the data span to query the 5 data after the third data in the persons document


3. Sort sort: 1 is in positive order and - 1 is in reverse order


Note: mongodb's key can store different types of data, and sorting also has priority
Minimum - > null - > number - > string - > Object / document - > array - > binary - > object ID - > Boolean - > date - > timestamp - > regular - > maximum

14.12 cursor

Traversing query data with cursor

var persons = db.persons.find();
  obj =;

Cursor several destruction conditions

1). The client sent him a message to destroy it
2). Cursor iteration completed
3). The default cursor will not be cleared even if it is useless for more than 10 minutes

14.13 aggregate query (Count, Distinct, Group)

1. count query results


2. Distinct de duplication

Please find out how many countries there are in people, and what are they

#key Represents the de duplication key

3. group grouping

db.runCommand({ group:{
  ns:"The name of the collection",
  key:"Group key object",
  initial:"Initialize accumulator",
  finalize:"Group completer"

Firstly, grouping will be performed according to the key. Each document in each group will execute the $reduce method. It receives two parameters, one is the record in the group, and the other is the accumulator data
Please find out the information of the students with the best math scores in each country in persons (must be above 90)

      prev.m = doc.m; = doc.m; =;
    prev.m =" comes from "" ,Math score is "+prev.m;

14.15 function formatting group key

If the key courtry and counTry exist simultaneously in the collection

    return {}
  return {country:doc.counTry}

15. MongoDB snapshot management

After the snapshot, the cursor will move for the invariant collection. See the usage

#Using snapshots requires advanced queries

Advanced Query options

$maxsaninteger maximum number of documents scanned
$mindoc query start
$maxEnd of doc query
$hintWhich index does doc use
$explainboolean statistics
$snapshotboolean consistent snapshot

15.1 the nearest 3 points of query point (70180){gis:{$near:[70,180]}},{_id:0,gis:1}).limit(3)

15.2. Query all points in the square with points (50, 50) and points (190190) as diagonals{gis:{$within:{$box:[[50,50],[190,190]]}}},{_id:0,gis:1})

15.3. Query the points in the center area under the rule that the center is (56,80) and the radius is 50{gis:{$with:{$center:[[56,80],50]}}},{_id:0,gis:1})

16. MongoDB user management

16.1. Add user

Add tom user for testdb

use testdb
db.createUser({user:"tom",pwd:"123",roles:[{ role:"dbAdmin",db:"testdb"}]})

Specific roles are
Read: allows the user to read the specified database
readWrite: allows users to read and write to the specified database
dbAdmin: allows users to perform administrative functions in the specified database, such as index creation, deletion, viewing statistics or accessing system profile
userAdmin: allows users to send messages to system The users collection is written, and users can be created, deleted and managed in the specified database
clusterAdmin: only available in the admin database. It gives users administrative rights to all partition and replica set related functions.
readAnyDatabase: it is only available in admin database and gives users read permission to all databases
readWriteAnyDatabase: only available in admin database, giving users read-write permission to all databases
userAdminAnyDatabase: only available in the admin database. Users are given userAdmin permissions on all databases
dbAdminAnyDatabase: only available in the admin database, giving users dbAdmin permissions for all databases.
root: available only in the admin database. Super account

16.2 view all users


Operations related to user management should basically run under the admin database, and use admin first;
If you are in a single database, you can only operate on the permissions of the current database

16.3. User deletion


16.4 view current user permissions


16.5 password modification

use testdb
db.changeUserPassword("tom", "123456")

1.6. Enable user


16.7 safety inspection -- auth

wrong testdb You cannot operate the database,Enable your own users to access
 wrong admin Database users cannot use database commands, admin The data in the database is authenticated as an administrator user

Pay attention to WeChat official account Tom structure and reply to "MongoDB" to get supporting information.

This article is the original of "Tom bomb architecture". Please indicate the source for reprint. Technology lies in sharing, I share my happiness! If you have any suggestions, you can also leave comments or private letters. Your support is the driving force for me to adhere to my creation. Focus on WeChat official account Tom structure, get more dry cargo!

It's not easy to be original. It's cool to insist. I've seen it here. Little partners remember to like, collect and watch it. Pay attention to it three times a button! If you think the content is too dry, you can share and forward it to your friends!

Topics: Java MongoDB