MongoDB 操作手册

MongoDB & pymongo 学习手册

MongDB Shell 下的操作。

pymongo 对于 MongoDB 的操作。

MongoDB Shell 下的操作

启动 MongoDB

# in MacOS or in linux
mongo
# in windows
mongo.exe

查看 database

show databases;

查看表

show tables;

db.restaurants.insert(
  {
    "name": "小明",
    "age": 20,
    "skills": [
        "python", "mongodb",
    ],
    "friends": [
      {
        "name": "小红",
        "age": 19,
        "skills": [
          "javascript",
        ],
      },
    ],
  }
)

# 查询所有条目
> db.restaurants.find()

# 按照字段查询
> db.restaurants.find( {<field>: <value>} )

# 字段条件查询
db.restaurants.find( { <field1>: { <operator1>: <value1> } } )
> # 大于
> db.restaurants.find( { <field1>: { $gt: <value1> } } ) 
> # 小于
> db.restaurants.find( { <field1>: { $lt: <value1> } } ) 

# 逻辑查询
> # and
> db.restaurants.find( {<field1>: <value1>, <field2>: <value2>} )
> # or
> db.restaurants.find( $or: [ {<field1>: <value1>}, {<field2>: <value2>} ] )

# 查询结果进行排序
> db.restaurants.find().sort( {<field>: <num>} ) (num=1 正序,num=2 倒序)

# 删除符合条件所有 documents 
> db.restaurants.remove( { <field>: <value> } )
# 仅删除符合条件的一个 document
> db.restaurants.remove( { <field>: <value> }, { justOne: true } )
# 删除 collection 中所有 documents
> db.restaurants.remove( { } )

# 查找符合条件的 documents 并更新相关字段
> db.restaurants.update( {<filed_query>: <value_query>}, { $set: { <filed_update>: <value_update> } } )

pymongo 使用手册

安装

1
pip install pymongo

创建链接

1
2
from pymongo import MongoClient
client = MongoClient(ip, port)

访问数据库对象

1
2
3
db = client.database
# 等价于
db = client["database"]

访问集合对象

1
2
3
collection = db.dataset
# 等价于
collection = db['dataset']

插入数据

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
from datetime import datetime
from pymongo import MongoClient
client = MongoClient()
db = client.test
# 向集合restaurants中插入一个文档。如果集合不存在,这个操作将创建一个新的集合。
result = db.restaurants.insert_one(
{
"address": {
"street": "2 Avenue",
"zipcode": "10075",
"building": "1480",
"coord": [-73.9557413, 40.7720266]
},
"borough": "Manhattan",
"cuisine": "Italian",
"grades": [
{
"date": datetime.strptime("2014-10-01", "%Y-%m-%d"),
"grade": "A",
"score": 11
},
{
"date": datetime.strptime("2014-01-16", "%Y-%m-%d"),
"grade": "B",
"score": 17
}
],
"name": "Vella",
"restaurant_id": "41704620"
}
)

该操作返回一个 InsertOneResult 对象

查询数据

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
from pymongo import MongoClient
client = MongoClient()
db = client.test
# 返回restaurants集合中所有文档并打印
cursor = db.restaurants.find()
for document in cursor:
print(document)
# 指定查询条件
## 格式: { <field1>: <value1>, <field2>: <value2>, ... }
### example
cursor = db.restaurants.find({"name": "youguess"})
# 在数组中查询
cursor = db.restaurants.find({"grades.grade": "B"})
# 使用操作符指定条件
## 格式 { <field1>: { <operator1>: <value1> } }
### 大于($gt)操作符
cursor = db.restaurants.find({"grades.score": {"$gt": 30}})
### 小于($lt)操作符
cursor = db.restaurants.find({"grades.score": {"$lt": 10}})
# 组合条件
## 逻辑与
cursor = db.restaurants.find({"cuisine": "Italian", "address.zipcode": "10075"})
## 逻辑或
cursor = db.restaurants.find(
{"$or": [{"cuisine": "Italian"}, {"address.zipcode": "10075"}]})

对查询结果排序

1
2
3
4
5
6
7
8
9
10
11
12
13
# pymongo.ASCENDING 表示升序排序
# pymongo.DESCENDING 表示降序排序
import pymongo
from pymongo import MongoClient
client = MongoClient()
db = client.test
# 并且先通过 borough 字段进行升序排序 然后在每个 borough 内,通过 address.zipcode 字段进行升序排序
cursor = db.restaurants.find().sort([
("borough", pymongo.ASCENDING),
("address.zipcode", pymongo.ASCENDING)
])

更新数据

可以使用update_one()update_many方法更新集合中的文档。update_one()方法一次更新一个文档。使用update_many()方法可以更新所有符合条件的文档。

不能更新_id字段。

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
53
from pymongo import MongoClient
client = MongoClient()
db = client.test
# 更新特定的字段
## 更新顶级字段
### 更新第一个符合name等于Juni这个条件的文档。使用$set操作符更新cuisine字段且将lastModified修改为当前日期。
result = db.restaurants.update_one(
{"name": "Juni"},
{
"$set": {
"cuisine": "American (New)"
},
"$currentDate": {"lastModified": True}
}
)
### 查看符合筛选器条件的文档数目
result.matched_count
### 查看更新操作中被修改的文档数目
result.modified_count
## 更新嵌入式文档中的字段
### 更新address字段中的street值
result = db.restaurants.update_one(
{"restaurant_id": "41156888"},
{"$set": {"address.street": "East 31st Street"}}
)
## 更新多个文档
### 更新所有的address.zipcode等于10016以及cuisine等于Other的文档,将cuisine字段设置为Category To Be Determined以及将lastModified更新为当前日期
result = db.restaurants.update_many(
{"address.zipcode": "10016", "cuisine": "Other"},
{
"$set": {"cuisine": "Category To Be Determined"},
"$currentDate": {"lastModified": True}
}
)
# 替换一个文档
## 替换整个文档(除了_id字段)更新操作后,被修改的文档将只剩下_id、name和address字段
result = db.restaurants.replace_one(
{"restaurant_id": "41704620"},
{
"name": "Vella 2",
"address": {
"coord": [-73.9557413, 40.7720266],
"building": "1480",
"street": "2 Avenue",
"zipcode": "10075"
}
}
)

删除数据

可以使用delete_one()以及delete_many()方法从集合中删除文档。方法需要一个条件来确定需要删除的文档。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
from pymongo import MongoClient
client = MongoClient()
db = client.test
# 删除所有符合条件的文档
result = db.restaurants.delete_many({"borough": "Manhattan"})
## 查看被删除的文档数目
result.deleted_count
# 删除所有文档
result = db.restaurants.delete_many({})
## 查看被删除的文档数目
result.deleted_count
# 销毁一个集合
db.restaurants.drop()
坚持原创技术分享,您的支持将鼓励我继续创作!