Python - 数据库(pyMongo)

下载 mongDB & pyMongo

pyMongo: https://pypi.python.org/pypi/pymongo/#downloads

mongoDB: https://www.mongodb.com/download-center#community

文档参考: http://www.runoob.com/mongodb/

 

运行mongoDB 

此处使用的是Window 32bit版本

mongod.exe --dbpath .\database --storageEngine=mmapv1

 

pyMongo 范例代码

#-*- coding: utf-8 -*-
import pymongo

class myMongo():
	def __init__(self):
		client = pymongo.MongoClient("localhost", 27017)
		
		self.db = client.test
		# self.db.authenticate("user","password") # 用户认证
		print self.db.name

	# 添加数据
	def insert(self, data):
		posts = self.db.posts
		posts.insert(data)
	
	# 删除数据
	def remove(self, conf=None):
		posts = self.db.posts
		if conf == None:
			posts.remove()
		else:
			posts.remove(conf)

	# 更新数据
	def update(self, conf, data):
		posts = self.db.posts
		posts.update(conf,{"$set": data})
	
	# 查询数据
	def find(self, conf=None):
		posts = self.db.posts

		data = None
		if conf == None:
			data = posts.find()
		else:
			data = posts.find(conf)
		return data

db = myMongo()
db.insert({"x": 10, "y": 100})
db.insert({"x": 15, "y": 100})
db.insert({"x": 20, "y": 100})

# x小于16
for item in db.find({"x": {"$lt": 16}}):
	print item

# x等于10
for item in db.find({"x": 10}):
	print item

条件查询

操作格式范例SQL
等于{<key>:<value>}posts.find({"x": 15})where x = 15
小于{<key>:{"$lt": <value>}}posts.find({"x":{"$lt": 15}})where x < 15
小于或等于{<key>:{"$lte": <value>}}posts.find({"x":{"$lte": 15}})where x <= 15
大于{<key>:{"$gt": <value>}}posts.find({"x":{"$gt": 15}})where x > 15
大于或等于{<key>:{"$gte": <value>}}posts.find({"x":{"$gte": 15}})where x >= 15
不等于{<key>:{"$ne": <value>}}posts.find({"x":{"$ne": 15}})where x != 15
操作格式范例SQL
AND   
OR   

转载于:https://my.oschina.net/cttmayi/blog/709371

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值