pymongo官网:https://api.mongodb.com/python/3.4.0/
pymongo安装:
pip install pymongo
导入
import pymongo
连接mongo对象
client= pymongo.MongoClient('mongodb://host:port')
指定数据库
db=client.test
#or db=client['test']
指定集合中的库
collection= db.student
#or collection= db['studnet']
插入数据(文档)
student={
'id':'1',
'name':'zs',
'age':12,
'gender':'m'
}
result= collection.insert_one( student )
print('新插入文档的编号(ObjectId):', result.inserted_id)
插入多条数据
student2={
'id':'1',
'name':'li',
'age':12,
'gender':'f'
}
student3={
'id':'1',
'name':'ww',
'age':12,
'gender':'m'
}
result= collection.insert_many( [student2, student3]) #生成多个ObjectId
id1= result.inserted_ids[0]
id2= result.inserted_ids[1]
print(result.inserted_ids)
条件查询
'''
$lt:< $gt:> $lte:<= $gte:>= %ne:!= $in $nin
'''
results= collection.find( {'age':{'$lte':12}})
for result in results:
print(result)
更新
condition= {'name':'zs','age':12}
student1={}
student1['age']=13
result= collection.update_many(condition, {'$set':student1})
print(result.matched_count,'-----',result.modified_count)
删除
result1= collection.delete_one( {'name':'ww'})
result2= collection.delete_many( {'age':{'$lte':20}})
print(result1.matched_count,'-----',result1.modified_count)
print(result2.matched_count,'-----',result2.modified_count)
功能符号
'''
$regex
$exists
$:type
$mod
$text
$where
参考网站:https://docs.mongodb.com/manual/reference/operator/query/
'''
#正则表达式
results= collection.find( {'name':{'$regex':'^w.*'}})
for result in results:
print(result)
排序
results= collection.find().sort( 'name', pymongo.ASCENDING)
print( [result['name'] for result in results])
偏移 -> 用于分页
results= collection.find().sort('name', pymongo.ASCENDING).skip(1).limit(2)
print( [result['name'] for result in results])
更多操作移步官网,以上内容仅此参考