MongoDB common commands

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

1. Create database

use testdb

2. Create collection

å

db.t_member.insert({name:"zhaomin",age:23})

3. Inquiry

db.t_member.find()
db.t_member.findOne()

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
db.t_member.drop();
#Delete database
db.dropDatabase();

6. View collection

show collections

7. View database

show dbs

8. Insert data

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

9. Batch update

db.t_member.update({name:"zhaomin"},{$set:{name:"zhanmin11"}},false,true);

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:

db.t_member.update({name:"zhangsan"},{$inc:{age:2}})

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

db.t_member.update({name:"zhangsan"},{$unset:{age:1}})

$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

db.t_member.update({name:"zhangsan"},{$pushAll:{classes:["English","Math","Chinese"]}});

$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

db.t_member.update({name:"zhangsan"},{$pull:{classes:["Chinese"]}}) 
#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:

db.t_member.update({"classes.type":"AA"},{$set:{"classes.$.sex":"male"}})

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

db.t_member.update({name:"zhangsan"},{$set:{classes:{$each:["chinese","art"]}}})

11. runCommand function and findAndModify function

runCommand({
  findAndModify:"persons",
  query:{Interrogator},
  sort:{sort},
  update:{Modifier},
  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:

ps=db.runCommand({
  findAndModify:"persons",
  query:{name:"zhangsan"},
  update:{$set:{name:"lisi"}},
  new:true
})
ps.value

12. System command example

1. Query server version number and host operating system

db.runCommand({buildInfo:1})

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

db.runCommand({collStats:"persons"})

3. View the last error message of this operation set

db.runCommand({getLastError:"persons"})

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

db.createCollection("mycoll",{size:100,capped:true,max:10})

Convert a normal set into a fixed set

db.runCommand({convertToCapped:"persons",size:1000})

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

db.mycoll.find().sort({$natural:-1})

14. MongoDB advanced query

db.t_member.find({},{_id:0,name:1})

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

db.t_member.find({age:{$gte:25,$lte:27}},{_id:0,name:1,age:1}) 
#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

db.t_member.find({country:{$in:["China","USA"]}},{_id:0,name:1:country:1}) 
#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
db.t_member.update({country:"China"},{$set:{sex:"m"}},false,true) 
#Add new keys to students of Chinese nationality sex 
db.t_member.find({sex:{$in:[null]}},{_id:0,name:1,sex:1}) 
#Find out sex by null People 

14.4 regular expressions

db.t_member.find({name:/li/i},{_id:0,name:1}) 
#"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

db.t_member.find({name:{$not:/li/i}},{_id:0,name:1}) 
#"The name does not exist in the query" li"Student information

14.6 use of $all and index

db.t_member.find({books:{$all:["JS","MONGODB"]}},{_id:0,name:1}) 
#Query like to see MONGOD and JS Students
db.t_member.find({"books.1":"JAVA"},{_id:0,name:1,books:1}) 
#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

db.t_member.find({books:{$size:4}},{_id:0,name:1}) 
#Find out the students who like 4 books

14.8. Find out students who like more than 4 books

1. Add size key

db.t_member.update({},{$set:{size:4}},false,true)

2. Add books and update size

db.t_member.update({name:"jim"},{$push:{books:"ORACL"},$inc:{size:1}})

3. Query more than 3 copies

db.t_member.find({size:{$gt:4}},{_id:0,name:1,size:1})

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

db.t_member.find({name:"jim"},{_id:0,name:1,books:{$slice:[1,3]}}) 
#Find out Jim 2nd in bookshelf~4 This book
db.t_member.find({name:"jim"},{_id:0,name:1,books:{$slice:-1}}) 
#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

db.t_member.find({school:{school:"K","score":"A"}},{_id:0,name:1})

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

db.t_member.find({"school.school":"K","school.score":"A"},{_id:0,name:1})

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

db.t_member.find({school:{$elemMatch:{school:"K",score:"A"}},{_id:0,name:1})
db.t_member.find({age:{$gt:22},books:"C++",school:"K"},{_id:0,name:1,age:1,books:1,school:1})

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:

db.t_member.find({},{_id:0,name:1}).limit(5)

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

db.t_member.find({},{_id:0,name:1}).limit(5).skip(3)

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

db.t_member.find({},{_id:0,name:1,age:1}).limit(5).skip(3).sort({age:1})

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();
  while(persons.hasNext()){
  obj = persons.next();
  print(obj.name)
}

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

db.persons.find({country:"USA"}).count()

2. Distinct de duplication

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

db.runCommand({distinct:"persons",key:"country"}).values 
#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",
  $reduce:"Resolver",
  condition:"condition",
  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)

db.runCommand({
  group:{
  ns:"persons",
  key:{"country":true},
  initial:{m:0},
  $reduce:function(doc,prev){
    if(doc.m>prev.m){
      prev.m = doc.m;
      prev.name = doc.m;
      prev.country = doc.country;
    }
  },
  condition:{m:{$gt:90}},
  finalize:function(prev){
    prev.m = prev.name+" comes from "+prev.country+" ,Math score is "+prev.m;
  }
 }
})

14.15 function formatting group key

If the key courtry and counTry exist simultaneously in the collection

$keyf:function(doc){
  if(doc.country){
    return {country:doc.country}
  }
  return {country:doc.counTry}
}

15. MongoDB snapshot management

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

db.persons.find({$query:{name:"Jim"},$snapshot:true}) 
#Using snapshots requires advanced queries

Advanced Query options

optionexplain
$query
$orderby
$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)

db.map.find({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

db.map.find({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

db.map.find({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

db.system.users.find()

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

db.system.users.remove({user:"tom"});

16.4 view current user permissions

db.runCommand({usersInfo:"tom",showPrivileges:true})

16.5 password modification

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

1.6. Enable user

db.auth("tom","123")

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