python版本:python3.5
pymongo的使用
代码:
#coding=utf8
from pymongo import *
# conn = MongoClient(host='192.168.1.188',port='27017')
client = MongoClient("mongodb://192.168.1.188:27017")
db_1 = client.test01 #方式1
db_2 = client['test01'] #方式2
col_1 = db_1.spider #方式1
col_2 = db_2['spider'] #方式2
#插入
data = {'id': 123, 'name': 'jike', 'age': 20, 'salary': 88888888}
col_1.insert(data)
#查找
# content = col_1.find({'age': 20})
content = col_1.find({})
print(type(content))
for row in content:
id = row['id']
name = row['name']
age = row['age']
print(id)
print(name)
print(age)
#更新
col_1.update_one({'age': 20}, {'$set':{'name': 'kingname'}})
col_1.update_many({'age': 20}, {'$set':{'age': 30}})
#删除
col_1.delete_one({'name': 'kingname'})
col_1.delete_many({'name': 'kingname'})
mongoengine
安装:
源码
#coding=utf-8
from mongoengine import *
#connect('blog', host='192.168.3.1', username='root', password='1234')
connect("test01",host='192.168.1.188',port=27017)
class Spider(Document):
pid = IntField()
name = StringField(required=True)
age = IntField(required=True)
salary = IntField()
spider01 = Spider(pid=1,name="sp1",age=33,salary=88888)
spider01.save()
spider02 = Spider(pid=2,name="sp2",age=55,salary=99999)
spider02.save()
for each in Spider.objects:
print(each.name)
print(each.age)
print(each.salary)
spider_list = Spider.objects(name="sp2")
print(spider_list)
print(type(spider_list))
for x in spider_list:
print(x.name)
spider_list.delete()