• notice
  • Congratulations on the launch of the Sought Tech site

MongoDB common commands (2)

1.Create database

use testdb

2.Create a collection

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

3.Query

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

4, modify

db.t_member.update({name:"zhaomin"},{$set:{age:18}}) # will not affect other attribute columns, primary key conflict will report an error
db.t_member.update({name:"zhaomin"},{$set:{age:18}},true)#If the third argument is true, execute the insertOrUpdate operation, update if the query is found, insert if not found ,or
var p=db.t_member.findOne();
db.t_member.update(p,{name:"zhaomin1"}) #Will wash out other attribute columns

5, wash off

db.t_member.remove({age:1}) #wash out the first item that satisfies the condition, only the data is washed, not the index
#wash off collection
db.t_member.drop();
#wash out the database
db.dropDatabase();

6.View Collection

show collections

7.View database

show dbs

8.Insert data

db.t_member.insert() # Do not allow duplicate key values
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 at the same time as the selector.The first false means that the insertOrUpdate operation is not performed, and the second true means that the batch operation is performed.

10, Updater

$set : Specify a key-value pair, modify it if it exists, add it if it does not exist
$inc : only used for numeric types, you can perform addition and subtraction operations for the numeric types of the specified key-value pair:

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

The result of the execution is that the age of the name "zhangsan" is added by 2
$unset : wash out the specified key

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

$push : Array key operation: 1.If the specified array exists, add a value to it; 2.If the specified array does not exist, create an array key and add a value; 3.If the specified key is not Array type, an error is reported;
$pushAll : batch insert values ​​into array keys

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

$addToSet : When there is this value in the specified array, it will not be inserted, otherwise it will be inserted

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

$pop: wash out the value of the specified array, when value=https://www.cnblogs.com/gupaoedu-tom/p/1 wash out the last value, when value=-1 wash out the first value

db.t_member.update({name:"zhangsan"},{$pop:{classes:1}}) #wash out the last value

$pull : wash out the value specified by the specified array

db.persons.update({name:"zhangsan"},{$pull:{classes:"Chinese"}}) #$pullAll batch wash out the specified array

db.t_member.update({name:"zhangsan"},{$pull:{classes:["Chinese"]}})
#If there are multiple Chinese in the array, wash them all

$ : When modifying the specified array, if the array has multiple objects, but only want to modify some of them, a locator is required:

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

$addToSet is combined with $each to complete batch array update operations

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

11, runCommand function and findAndModify function

runCommand({
findAndModify:"persons",
query:{queryer},
sort:{sort},
update:{modifier},
new:true Whether to return the modified data
});

The runCommand function executes special functions in mongdb
findAndModify is one of the special functions, which is used to return the file after executing the return 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 the server version number and host operating system

db.runCommand({buildInfo:1})

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

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

3.View the last error message of this collection

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

13, fixed set

1.Features

The fixed set has no index by default, even _id has no index.Since it does not need to allocate new space, its insertion speed is very fast.The order of the fixed set is determined and the query speed is very fast.The most suitable is the log Manage

2.Create a fixed collection

The required size to create a new fixed collection is 100 bytes, and 10 files can be saved to disk

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

Convert a normal set to a fixed set

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

3.Reverse the sorting of the fixed set, the default is the order of insertion

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

14, MongoDB advanced query

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

The first empty bracket means to query all the data, the value in the second bracket means 0 means no return, and the value 1 means return, by default, if the primary key is not specified, the primary key will always be returned;

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

Comparison operator: $lt: < $lte: <=$gt: > $gte: >=$ne: !=

14.1, query conditions

db.t_member.find({age:{$gte:25,$lte:27}},{_id:0,name:1,age:1})
#Query people whose age is greater than or equal to 25 and less than or equal to 27
db.t_member.find({country:{$ne:"Korea"}},{_id:0,name:1,country:1})
#Query the math scores of all people whose nationality is not Korean

14.2, inclusion and exclusion (arrays only)

$in or $nin

db.t_member.find({country:{$in:["China","USA"]}},{_id:0,name:1:country:1})
#Check 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 score is greater than 85 or English is greater than 90
db.t_member.update({country:"China"},{$set:{sex:"m"}},false,true)
#Add a new key sex to students of Chinese nationality
db.t_member.find({sex:{$in:[null]}},{_id:0,name:1,sex:1})
#Query the person whose sex is null

14.4, regular expressions

db.t_member.find({name:/li/i},{_id:0,name:1})
#Query the information of students with "li" in their names

14.5, $not use

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

db.t_member.find({name:{$not:/li/i}},{_id:0,name:1})
#Query the information of students whose name does not exist in "li"

14.6, $all and index use

db.t_member.find({books:{$all:["JS","MONGODB"]}},{_id:0,name:1})
#Query students who like to watch MONGOD and JS
db.t_member.find({"books.1":"JAVA"},{_id:0,name:1,books:1})
#Query the second book is the learning information of JAVA

14.7, the use of $size cannot be used with the comparison query

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

14.8.Find out the student who likes more than 4 books in the student book

1.Increase the size key

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

2.Add books and update size at the same time

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, $slice operator returns the internal value of the specified array in the file

db.t_member.find({name:"jim"},{_id:0,name:1,books:{$slice:[1,3]}})
#Query the 2nd~4th book in Jim's bookshelf
db.t_member.find({name:"jim"},{_id:0,name:1,books:{$slice:-1}})
# Query out the last book

14.10, file query

Check out the students who attended K and got A grades

1.Absolute query, the order and the number of keys should be exactly the same

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

2.Object method, but there will be errors, multiple conditions may go to multiple objects to query

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

3.Correct way to query $elemMatch with 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 records to query the first 5 data in the persons file:

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

2.Specify the data span to query the 5 data after the 3rd data in the persons file

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

3, sort sort 1 is positive order,-1 is reverse order

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

14.12, Cursor

Using the cursor to traverse the query data

var persons=db.persons.find();
while(persons.hasNext()){
obj=persons.next();
print(obj.name)
}

Several Cursor Destruction Conditions

1).The client sends information to tell him to destroy
2).Cursor iteration is complete
3).The default cursor will not be cleared if it is useless for more than 10 minutes

14.13 Aggregate query (Count, Distinct, Group)

1, count the number of query results

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

2, Distinct deduplication

Please find out how many countries are there in persons

db.runCommand({distinct:"persons",key:"country"}).values
#key represents the key to deduplicate

3, group grouping

db.runCommand({ group:{
ns:"set name",
key:"Group key object",
initial:"initialize the accumulator",
$reduce:"Reducer",
condition: "condition",
finalize:"group finalizer"
}})

The grouping will first be grouped according to the key.Each file in each group must execute the $reduce method.It receives 2 arguments, 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 the 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 Grouping Key

If both keys Counrty and counTry exist 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 be moved for the immutable collection.Let's see how to use it.

db.persons.find({$query:{name:"Jim"},$snapshot:true})
# With snapshot, you need to use advanced query

Advanced query options

Options Explanation
$query
$orderby
$maxsan integer maximum number of files to scan
$min doc query starts
$max doc query end
$hint Which index the doc uses
$explain boolean statistics
$snapshot boolean consistent snapshot

15.1, query point (70,180) nearest 3 points

db.map.find({gis:{$near:[70,180]}},{_id:0,gis:1}).limit(3)

15.2, query all points in a square with point (50, 50) and point (190, 190) as diagonal The point

db.map.find({gis:{$within:{$box:[[50,50],[190,190]]}}},{_id:0,gis:1})

15.3.Find the points in the area of ​​the circle with thecenteras (56,80) and the radius as 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"}]})

The specific roles are
read: allows the user to read the specified database
readWrite: Allows the user to read and write to the specified database
dbAdmin: Allows users to perform administrative functions in the specified database, such as index creation, washing, viewing statistics or accessing system.profile
userAdmin: allows users to write to the system.users collection, and can create, wash and manage users in the specified database
clusterAdmin: Only available in the admin database, grants the user administrative rights to all functions related to shards and replica sets,
readAnyDatabase: only available in the admin database, giving the user read permission for all databases
readWriteAnyDatabase: only available in the admin database, giving the user read and write permissions for all databases
userAdminAnyDatabase: only available in the admin database, giving the user userAdmin permissions for all databases
dbAdminAnyDatabase: only available in the admin database, giving the user dbAdmin privileges for all databases,
root: only available in the admin database, super account, super privilege

16.2 View All Users

db.system.users.find()

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

16.3, User washout operation

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

16.4 View current user permissions

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

16.5 Change Password

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

1.6, Enable User

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

16.7, security check--auth

Non-testdb can't operate the database, you can only access it by enabling your own user
Users who are not in the admin database cannot use database commands.The data in the admin database are authenticated as administrator users.

It's not easy to be original, but it's cool to stick to it.I've seen it here.Friends remember to like, bookmark, watch, and follow it three times with one click! If you think the content is too dry, you can share it and forward it to your friends to nourish and nourish!

Tags

Technical otaku

Sought technology together

Related Topic

0 Comments

Leave a Reply

+