pymongo 增、删、改、查等操作

pymongo 的基本操作

1. 连接mongodb

import pymongo

client = pymongo.MongoClient(host='localhost', port=27017)

2. 选择数据库和集合

已有的数据库和集合会选中,没有的会自动创建

# 选择数据库,没有则创建test数据库
db = client.test
# 选择集合,没有则创建students集合
collection = db.students

3. 插入数据

3.1 插入一条数据
  • insert_one
student = {
   
    'id': '20150801',
    'name': 'ergou',
    'age': 20,
    'gender': 'male'
}

result = collection.insert_one(student)
print(result)
3.2 插入多条数据
  • insert_many
student1 = {
   
	'id': '20150801',
    'name': 'ergou',
    'age': 20,
    'gender': 'male'
}
student2 = {
   
	'id': '20150801',
    'name': 'ergou',
    'age': 20,
    'gender'
阅读终点,创作起航,您可以撰写心得或摘录文章要点写篇博文。去创作
  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
Python操作MongoDB的方法如下: 1. 连接MongoDB数据库 使用pymongo库连接MongoDB数据库,代码如下: ```python import pymongo client = pymongo.MongoClient("mongodb://localhost:27017/") db = client["mydatabase"] ``` 2. 插入数据 使用insert_one()或insert_many()方法向MongoDB数据库中插入一条或多条数据,代码如下: ```python # 插入单条数据 mycollection = db["customers"] mydict = { "name": "John", "address": "Highway 37" } x = mycollection.insert_one(mydict) # 插入多条数据 mylist = [ { "name": "Amy", "address": "Apple st 652"}, { "name": "Hannah", "address": "Mountain 21"}, { "name": "Michael", "address": "Valley 345"}, { "name": "Sandy", "address": "Ocean blvd 2"}, { "name": "Betty", "address": "Green Grass 1"}, { "name": "Richard", "address": "Sky st 331"} ] x = mycollection.insert_many(mylist) ``` 3. 询数据 使用find()方法询MongoDB数据库中的数据,代码如下: ```python # 询所有数据 for x in mycollection.find(): print(x) # 询指定数据 myquery = { "address": "Park Lane 38" } mydoc = mycollection.find(myquery) for x in mydoc: print(x) ``` 4. 更新数据 使用update_one()或update_many()方法更新MongoDB数据库中的数据,代码如下: ```python # 更新单条数据 myquery = { "address": "Valley 345" } newvalues = { "$set": { "address": "Canyon 123" } } mycollection.update_one(myquery, newvalues) # 更新多条数据 myquery = { "address": { "$regex": "^S" } } newvalues = { "$set": { "name": "Minnie" } } x = mycollection.update_many(myquery, newvalues) ``` 5. 除数据 使用delete_one()或delete_many()方法除MongoDB数据库中的数据,代码如下: ```python # 除单条数据 myquery = { "address": "Mountain 21" } mycollection.delete_one(myquery) # 除多条数据 myquery = { "address": {"$regex": "^S"} } x = mycollection.delete_many(myquery) ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

qq_42847500

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值