# Python操作MongoDB数据库
# MongoDB 原生语句
# 安装pymongo
pip install pymongo
# Python连接MongoDB
import pymongo
# mobgodb连接对象
client = pymongo.MongoClient('localhost', port=27017)
# 获取数据库, 可以不用创建数据库
db = client.zhihu
# 获取数据库中的集合
collection = db.qa
# insert_one 写入数据
collection.insert_one({
"username":"aaa",
"password":'123456'
})
# insert_many 写入多条数据
collection.insert_many([
{
"username":"aaa",
"age":18
},
{
"username":"bbb",
"age":20
}
])
# find 查找所有数据
cursor = collection.find()
for x in cursor:
print(x)
# find_one 获取一条数据
result = collection.find_one()
print(result)
# 添加查询条件
result = collection.find_one({"age":18})
print(result)
# 更新数据
collection.update_one({"username":"bbb"},{"$set":{"username":"spider"}})
# 更新多条数据
collection.update_many({"username":"aaa"},{"$set":{"username":"spider"}})
# 删除一条数据
collection.delete_one({"age":18})
# 删除多条数据
collection.delete_many({"username":'spider'})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52