Python操作MongoDB

139 阅读2分钟
连接数据库
[Python]
纯文本查看
复制代码
01
02
03
04
05
06
07
08
09
10
11
12
13
import pymongo
# 连接到数据库,以下两种方式均可
client = pymongo.MongoClient(host='localhost', port=27017)
client = pymongo.MongoClient('mongodb://localhost:27017')
# 指定连接的数据库,以下两种方式均可
db = client.demo
db = client['demo']
# 指定数据库的某个集合,以下两种方式均可
collection = db.demo_1
collection = db['demo_1']
插入数据
  • insert_one(), 一次插入一条记录
  • insert_many(), 一次插入多条记录
mongo默认会给每一条记录添加一个_id字段,用来唯一标识每一条记录。
[Python]
纯文本查看
复制代码
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
# 一次插入一条记录
book = {
'name': '五年高考三年模拟',
'price': 50,
}
result = collection.insert_one(book)
print(result.inserted_id)
# 一次插入多条数据
book = [
{
'name': '五年高考',
'price': 50,
},
{
'name': '三年模拟',
'price': 30,
},
]
resutl = collection.insert_many(book)

查询数据
  • find_one(), 查询一条记录, 以字典的形式直接返回数据结果。
  • find(), 查询多条记录, 返回的是Cursor对象,需要遍历才能获取数据
[Python]
纯文本查看
复制代码
1
2
3
4
5
6
7
8
# 查询单条记录
results = collection.find_one({'name': '五年高考'})
print(result)
# 查询多条记录
results = collection.find({'price': 50})
for result in results:
print(result)

更新数据
  • update_one(), 只更新匹配到的第一条记录
  • update_many(), 更新匹配到的全部记录
[Python]
纯文本查看
复制代码
01
02
03
04
05
06
07
08
09
10
condition = {'name':'五年高考'}
price_change = {'price': 100}
# 方式1
result = collection.update_one(condition,price_change)
print(result)
# 方式2
result = collection.update_one(condition, {'$set': price_change})
print(result)

方式一:
相当于查询到name为五年高考的字段,将其删除,再将待更新的数据添加上去。结果就是只剩下一个price为100的数据。
方式二:
查询到name为五年高考的字段,仅仅是将price更新为了100,其余不动。
另外可以调用result.matched_count, result.modified_count来查看匹配的条数和影响的条数。
删除数据
  • delete_one(), 删除符合条件的第一条数据
  • delete_many(), 删除符合条件的全部数据
[Python]
纯文本查看
复制代码
1
2
3
4
5
6
7
# 删除一条
result = collection.delete_one({'name': '五年高考'})
print(result)
# 删除多条
result = collection.delete_many({'price':50}) # 删除价格为50的全部记录
result = collection.delete_many({'price':{'$gt':30}}) # 删除价格大于30的全部记录

其他常用方法
  • count()
[Python]
纯文本查看
复制代码
1
2
count = collection.find().count() # 查询表中全部记录的条数
count = collection.find({'price': {'$gt':30}}).count() # 价格大于30的条数

  • sort()
[Python]
纯文本查看
复制代码
1
2
results = collection.find().sort('name', pymongo.ASCENDING) # 按照name升序返回结果
results = collection.find().sort('price', pymongo.DECENDING) # 按照price降序返回结果

  • limit()
[Python]
纯文本查看
复制代码
1
results = collection.find().sort('name', pymongo.ASCENDING).limit(2) # 限制返回两条结果

备注:上述部分转自网络,如有侵权,请联系小编删除。

更多Java学习资料可关注:itheimaGZ获取