Python MongoDB Operations Encyclopedia

Source: Internet
Author: User

Database
Increase
Use DB1 #有则切换, none added

Check
Show DBS #查看所有
DB #当前

By deleting
Db.dropdatabase ()

Collection:
Increase:
Db.user
Db.user.info
Db.user.auth

View
Show collections
Show tables

By deleting
Db.user.info.drop ()

Document:
Increase
Db.user.insert ({"_id": 1, "name": "Egon"})
user0={
"Name": "Egon",
"Age": 10,
' Hobbies ': [' music ', ' read ', ' Dancing '],
' Addr ': {
' Country ': ' China ',
' City ': ' BJ '
}
}

Db.user.insert (USER0)
Db.user.insertMany ([User1,user2,user3,user4,user5])

Db.t1.insert ({"_id": 1, "a": 1, "B": 2, "C": 3})
#有相同的_id则覆盖, no same _id is added, you must specify _ID
Db.t1.save ({"_id": 1, "Z": 6})
Db.t1.save ({"_id": 2, "Z": 6})
Db.t1.save ({"Z": 6})

The difference between save and insert:
If there is a primary key in the new data, insert () prompts for an error, and save () changes the original content to the new content.
Such as:
Data already exists: {_id:1, ' name ': ' N1 '}, when the insert operation is performed again,
Insert ({_id:1, "name": "N2"}) will report a duplicate error prompt for the primary key
Save ({_id:1, "name": "N2"}) will change N1 to N2.
Same point:
If there is no primary key in the new data, a record is added.
Data already exists: {_id:1, ' name ': ' N1 '}, when the insert operation is performed again,
Insert ({"name": "N2"}) inserted data because there is no primary key, so it will add a piece of data
Save ({"name": "N2"}) adds a single piece of data.
Check

Comparison operation: =,!=,>,<,>=,<=
#1, select * from db1.user where id = 3
Db.user.find ({"_id": 3})

#2, select * from Db1.user where id! = 3
Db.user.find ({"_id": {"$ne": 3}})

#3, select * from Db1.user where ID > 3
Db.user.find ({"_id": {"$GT": 3}})

#4, select * from Db1.user where < 3
Db.user.find ({"Age": {"$lt": 3}})

#5, select * from Db1.user where ID >= 3
Db.user.find ({"_id": {"$gte": 3}})

#6, select * from Db1.user where ID <= 3
Db.user.find ({"_id": {"$lte": 3}})


#逻辑运算: $and, $or, $not
#1 SELECT * from Db1.user where ID >=3 and ID <=4;
Db.user.find ({"_id": {"$gte": 3, "$lte": 4}})

#2 SELECT * from Db1.user where ID >=3 and ID <=4 and >=40;
Db.user.find ({
"_id": {"$gte": 3, "$lte": 4},
"Age": {"$gte": 40}
})

Db.user.find ({"$and": [
{"_id": {"$gte": 3, "$lte": 4}},
{"Age": {"$gte": 40}}
]})


#3 SELECT * from Db1.user where ID >=0 and ID <=1 or id >=4 or name = "Yuanhao";
Db.user.find ({"$or": [
{"_id": {"$lte": 1, "$gte": 0}},
{"_id": {"$gte": 4}},
{"Name": "Yuanhao"}
]})

#4 SELECT * from Db1.user where id% 2 = 1;
Db.user.find ({"_id": {"$mod": [2,1]}})


Db.user.find ({
"_id": {"$not": {"$mod": [2,1]}}
})

#成员运算: $in, $nin
Db.user.find ({"name": {"$in": ["Alex", "Egon"]}})
Db.user.find ({"name": {"$nin": ["Alex", "Egon"]}})


#正则匹配
SELECT * from Db1.user where name regexp "^jin.*? (g|n) $ ";
Db.user.find ({
"Name":/^jin.*? (g|n) $/i
})


#查看指定字段
Select Name,age from Db1.user where name regexp "^jin.*? (g|n) $ ";
Db.user.find ({
"Name":/^jin.*? (g|n) $/i
},
{
"_id": 0,
"Name": 1,
"Age": 1
}
)

#查询数组相关
Db.user.find ({
"Hobbies": "Dancing"
})

Db.user.find ({
"Hobbies": {"$all": ["Dancing", "Tea"]}
})

Db.user.find ({
"Hobbies.2": "Dancing"
})

Db.user.find (
{},
{
"_id": 0,
"Name": 0,
"Age": 0,
"Addr": 0,
"Hobbies": {"$slice": [+]},
}
)


Db.user.find (
{},
{
"_id": 0,
"Name": 0,
"Age": 0,
"Addr": 0,
"Hobbies": {"$slice": 2},
}
)


Db.user.find (
{
"Addr.country": "China"
}
)

Db.user.find (). Sort ({"_id": 1, "Age":-1})


Db.user.find (). Limit (2). Skip (0)
Db.user.find (). Limit (2). Skip (2)
Db.user.find (). Limit (2). Skip (4)
Db.user.find (). DISTINCT ()

Change
One syntax:
Db.table.update (
Conditions
Modify Fields,
Other parameters
)

Update db1.t1 set id=10 where name= "Egon";

Db.table.update (
{},
{"Age": 11},
{
"Multi": true,
"Upsert": True
}
)

1, update db1.user set age=23,name= "Wuhan University Lang" where name= "Wupeiqi";
#覆盖式
Db.user.update (
{"Name": "Wupeiqi"},
{"Age": +, "name": "Wuhan University Lang"}
)
#局部修改: $set
Db.user.update (
{"Name": "Alex"},
{"$set": {"age": Pan Jinlian, "name": "-alex"}}
)

#改多条
Db.user.update (
{"_id": {"$gte": 1, "$lte": 2}},
{"$set": {"age": 53,}},
{"Multi": true}
)
#有则修改, none added
Db.user.update (
{"Name": "EGON"},
{"$set": {"name": "EGON", "Age": 28,}},
{"Multi": true, "Upsert": true}
)

#修改嵌套文档
Db.user.update (
{"Name": "Pan Jinlian-alex"},
{"$set": {"addr.country": "Japan"}}
)

#修改数组
Db.user.update (
{"Name": "Pan Jinlian-alex"},
{"$set": {"hobbies.1": "Piao"}}
)

#删除字段
Db.user.update (
{"Name": "Pan Jinlian-alex"},
{"$unset": {"Hobbies": ""}}
)

2. $inc
Db.user.update (
{},
{"$inc": {"Age": 1}},
{"Multi": true}
)

Db.user.update (
{},
{"$inc": {"Age":-10}},
{"Multi": true}
)

3, $push, $pop $pull
Db.user.update (
{"Name": "Yuanhao"},
{"$push": {"Hobbies": "Tangtou"}},
{"Multi": true}
)

Db.user.update (
{"Name": "Yuanhao"},
{"$push": {"Hobbies": {"$each": ["Tattoo", "Smoking"]}},
{"Multi": true}
)

#从头删-1, delete 1 from the tail
Db.user.update (
{"Name": "Yuanhao"},
{"$pop": {"Hobbies":-1}},
{"Multi": true}
)

Db.user.update (
{"Name": "Yuanhao"},
{"$pop": {"Hobbies": 1}},
{"Multi": true}
)

#按条件删
Db.user.update (
{"Name": "Yuanhao"},
{"$pull": {"Hobbies": "Tattoo"}},
{"Multi": true}
)

#3, $addToSet
Db.t3.insert ({"URLs": []})
Db.t3.update (
{},
{"$addToSet": {"URLs": {"$each": [
"Http://www.baidu.com",
"Http://www.baidu.com",
"Http://www.baidu.com",
"Http://www.baidu.com",
"Http://www.baidu.com"
]}}},
{"Multi": true}
)


By deleting
Db.user.deleteOne ({"_id": {"$gte": 3}})
Db.user.deleteMany ({"_id": {"$gte": 3}})
Db.user.deleteMany ({})


Polymerization
One: $match
Cases:
Select post from Db1.emp where the > GROUP by post has AVG (salary) > 10000;

# $match
#1, select * from db1.emp where > 20
Db.emp.aggregate ({"$match": {"age": {"$GT": 20}})

# $group
#2, select post from db1.emp where Age > Group by post;
Db.emp.aggregate (
{"$match": {"age": {"$GT": 20}},
{"$group": {"_id": "$post"}}
)

#3, select Post,avg (Salary) as avg_salary from Db1.emp where the Age > group by post;
Db.emp.aggregate (
{"$match": {"age": {"$GT": 20}},
{"$group": {"_id": "$post", "avg_salary": {"$avg": "$salary"}}}
)

#select post from Db1.emp where the Age > GROUP by post has AVG (salary) > 10000;
Db.emp.aggregate (
{"$match": {"age": {"$GT": 20}},
{"$group": {"_id": "$post", "avg_salary": {"$avg": "$salary"}},
{"$match": {"avg_salary": {"$GT": 10000}}
)

Two: Projection
{"$project": {"field name to keep": 1, "Field name to remove": 0, "new field name": "Expression"}}
Example 1:
Db.emp.aggregate (
{"$project": {"_id": 0, "name": 1, "POST": 1, "annual_salary": {"$multiply": [[], "$salary"]}},
{"$group": {"_id": "$post", "average yearly salary": {"$avg": "$annual _salary"}}},
{"$match": {"Average yearly salary": {"$GT": 1000000}},
{"$project": {"department name": "$_id", "average yearly salary": 1, "_id": 0}}
)

Example 2:
Db.emp.aggregate (
{"$project": {"_id": 0, "name": 1, "Hire_period": {"$subtract": [New Date (), "$hire _date"]}}}
)


Db.emp.aggregate (
{"$project": {"_id": 0, "name": 1, "Hire_year": {"$year": "$hire _date"}}}
)

Db.emp.aggregate (
{"$project": {"_id": 0, "name": 1, "Hire_period": {"$subtract": [{"$year": New Date ()},{"$year": "$hire _date"}]}}}
)

Example 3:
Db.emp.aggregate (
{"$project": {"_id": 0, "new_name": {"$toUpper": "$name"},}}
)

Db.emp.aggregate (
{"$match": {"name": {"$ne": "Egon"}}},
{"$project": {"_id": 0, "new_name": {"$concat": ["$name", "_SB"]},}}
)

Db.emp.aggregate (
{"$match": {"name": {"$ne": "Egon"}}},
{"$project": {"_id": 0, "new_name": {"$substr": ["$name", 0,3]},}}
)

Three: {"$group": {"_id": Group field, "new field name": Aggregation operator}}

#select Post,max,min,sum,avg,count,group_concat from Db1.emp group by post;

Db.emp.aggregate (
{"$group": {
"_id": "$post",
"Max_age": {"$max": "$age"},
"min_id": {"$min": "$_id"},
"Avg_salary": {"$avg": "$salary"},
"Sum_salary": {"$sum": "$salary"},
"Count": {"$sum": 1},
"Names": {"$push": "$name"}
}
}
)


Four: Sort: $sort, limit: $limit, skip: $skip
Db.emp.aggregate (
{"$match": {"name": {"$ne": "Egon"}}},
{"$project": {"_id": 1, "new_name": {"$substr": ["$name", 0,3]}, "Age": 1}},
{"$sort": {"Age": 1, "_id":-1}},
{"$skip": 5},
{"$limit": 5}
)


# add
Db.emp.aggregate ({"$sample": {"Size": 3}}) #随机选取3个文档

Python MongoDB Operations Encyclopedia

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.