python基础操作mongodb

因为在代码中有详细的注释就不多讲解了。

pymongo的安装:pip install pymongo


from pymongo import *

# 建立链接
client = MongoClient()


# 链接shihao数据库
db = client.shihao

# 链接xiaohao的集合(表)
collection = db.xiaohao

# 填写数据
mydata = {"name":"water", "sex":"male","job":"student"}


# 插入
collection.insert(mydata)

collection.insert_one({
    "borough": "Manhattan",
    "cuisine": "Italian",
    "name": "Vella",
    "restaurant_id": "41704620"
})

# 因为insert_many插入的数list所以要转换一下
alist = []
alist.append(mydata)
collection.insert_many(alist)

collection.find()


# 查看
# find_one()显示满足条件的第一个collection,find() 的结果则是一个满足条件的对象数组


# 可以使用for-in 循环进行查看:
print collection.find({"name":"water"})[0]
print collection.find({"name":"water"})[1]
# 统计结果总条数
print collection.find_one({"name":"water", "sex":"male"})
print collection.find().count()

# 这样的查询符号有$lt(小于),$gt(大于),$lte(小于等于),$gte(大于等于),$ne(不等于),这与原生 MongoDB 中相同。
print collection.find({"age": {"$lt": 30}})

# 排序
print collection.find().sort("age")


# 更新
temp = collection.find_one({"name":"water"})

temp2 = temp.copy()
temp["name"] = "Jordan"

# 或 .update() ,注意参数形式collection.update(temp, temp2)
# .replace_one()需要传入两个参数,分别为当前document和要更新为的document
collection.save(temp)

# collection.remove(temp)


  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

_我走路带风

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

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

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

打赏作者

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

抵扣说明:

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

余额充值