MongoDB学习笔记5——Python和MongoDB
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了MongoDB学习笔记5——Python和MongoDB,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含7078字,纯文字阅读大概需要11分钟。
内容图文
![MongoDB学习笔记5——Python和MongoDB](/upload/InfoBanner/zyjiaocheng/876/1b35008c2da24a6bb75009c1f2570f98.jpg)
1. MongoDB使用BSON样式的文档,在Python中使用的是字典。
2.使用PyMongo模块
1)连接和断开
from pymongo import MongoClient
c = MongoClient()
db = c.library (其中library是数据库)
collection = db.items (items是集合)
2)插入数据
item = {
"Type" : "Laptop",
"ItemNumber" : "1234EXD",
"Status" : "In use",
"Location" : {
"Department" : "Development",
"Building" : "2B",
"Floor" : 12,
"Desk" : 120101,
"Owner" : "Andreson, Thomas"
},
"Tags" : ["Laptop","Development","In Use"]
}
将数据插入到集合中:
collection.insert_one(item)
如果遇到多组数据的情况:
two = [{
"Type" : "Laptop",
"ItemNumber" : "2345EXD",
"Status" : "In use",
"Location" : {
"Department" : "Development",
"Building" : "2B",
"Floor" : 12,
"Desk" : 120102,
"Owner" : "Smith, Simon"
},
"Tags" : ["Laptop", "Development", "In Use"]
},
{
"Type" : "Laptop",
"ItemNumber" : "3456TFS",
"Status" : "In use",
"Location" : {
"Department" : "Development",
"Building" : "2B",
"Floor" : 12,
"Desk" : 120103,
"Owner" : "Smith, Simon"
},
"Tags" : ["Laptop", "Development", "In Use"]
}]
使用
collection.insert_many(two)
3)搜索数据
3-1)搜索单个文档
collection.find_one() (没有其他限制条件默认返回第一个文档)
collection.find_one({"ItemNumber":"3456TFS"}, {'_id':False})(有限制条件,不显示'_id')
3-2)搜索多个文档
for doc in collection.find():
doc
for doc in collection.find({"Location.Owner":"Andreson, Thomas"}):
doc
3-3)使用点操作符
for doc in collection.find({"Location.Department":"Development"}):
doc
3-4)返回字段
for doc in collection.find({'Status':'In use'},{'ItemNumber':True,'Location.Owner':True}):
doc
3-5)使用sort()、limit()和skip()简化查询
for doc in collection.find({'Status':'In use'},{'ItemNumber':True,'Location.Owner':True}).sort('ItemNumber'):
doc
for doc in collection.find({},{'ItemNumber':True}).limit(2):
doc
for doc in collection.find({'Status':'In use'},{'ItemNumber':True,'Location.Owner':True}).limit(2).skip(1).sort('ItemNumber'): (跳过一个,输出两个,按照要求排序)
doc
3-6)聚集查询
3-6-1)使用count()统计数目
collection.count()
3-6-2)使用distinct()统计唯一数据的数目
collection.distinct('ItemNumber') (无重复)
3-6-3)使用聚集框架对数据分组
collection.aggregate([
{'$unwind':'$Tags'},
{'$group':{'_id':'$Tags','Totals':{'$sum':1}}}
])
按照特定指示输出数据
from bson.son import SON
collection.aggregate([
{'$unwind':'$Tags'},
{'$group':{'_id':'$Tags','Totals':{'$sum':1}}},
{'$sort':SON([('Totals',-1)])}
])
3-7)使用hint()指定索引
from pymongo import ASCENDING
collection.create_index([("ItemNumber",ASCENDING)])
for doc in collection.find({"Location.Owner":"Smith, Simon"}).hint([("ItemNumber",ASCENDING)]):
doc
3-8)使用条件操作符定义查询
3-8-1)使用$lt、$gt、$lte和$gte操作符
for doc in collection.find({"Location.Desk":{"$lt":120102}}):
doc
for doc in collection.find({"Location.Desk":{"$gt":120102}}):
doc
3-8-2)使用$ne搜索不匹配的数据
for doc in collection.find({"Status":{"$ne":"In use"}}):
doc
3-8-3)使用$in搜索不匹配的数据
for doc in collection.find({"Tags":{"$in":["Not used","Development"]}},{"ItemNumber": True}).limit(2)
doc
3-8-4)使用$nin指定不匹配的数组
for doc in collection.find({"Tags":{"$nin":["Development"]}},{"ItemNumber":True}):
doc
3-8-5)搜索匹配数组值的文档
for doc in collection.find({"Tags":{"$all":["Storage","Not used"]}},{"ItemNumber":True}):
doc
3-8-6)使用$or指定多个匹配表达式
for doc in collection.find({"$or":[{"Location.Department":"Storage"},{"Location.Owner":"Anderson, Thomas"}]}):
doc
3-8-7)使用$slice从数组中获取元素
重新输入一组数据
chair = ({
"Status":"Not used",
"Tags":["Chair","Not used","Storage"],
"ItemNumber":"6789SID",
"Location":{
"Department":"Storage",
"Building":"2B"
},
"PreviousLocation":["120100","120101","120102","120103","120104","120105","120106","120107","120108","120109","120110"]
})
collection.insert_one(chair)
collection.find_one({'ItemNumber':'6789SID'},{'PreviousLocation':{'$slice':3}})
collection.find_one({'ItemNumber':'6789SID'},{'PreviousLocation':{'$slice':-3}})
collection.find_one({'ItemNumber':'6789SID'},{'PreviousLocation':{'$slice':[5,3]}})
3-8-9)使用正则表达式执行搜索
import re
for doc in collection.find({'ItemNumber':re.compile('4')},{'ItemNumber':True}):
doc
for doc in collection.find({'ItemNumber':re.compile('.FS$')},{'ItemNumber':True}):
doc
for doc in collection.find({'Location.Owner':re.compile('^anderson.',re.IGNORECASE)},{'ItemNumber':True,'Location.Owner':True}):
doc
3-9)修改数据
3-9-1)更新数据
update = ({
"Type":"Chair",
"Status":"Not used",
"Tags":["Chair","Not used","Storage"],
"ItemNumber":"6789SID",
"Location":{
"Department":"Storage",
"Building":"2B",
"DeskNumber":131131,
"Owner":"Martin, Lisa"
}
})
collection.update_one({"ItenNumber":"6789SID"},update)
3-9-2)修改操作符
使用$inc增加整数值:
collection.update_one({"ItemNumber":"6789SID"},{"$inc":{"Location.DeskNumber":20}})
使用$set修改现有值:
collection.update_many({"Location.Department":"Development"},{"$set":{"Location.Building":"3B"}})
使用$unset移除键/值字段:
collection.update_one({"Status":"Not used","ItemNumber":"2345FDX"},{"$unset":{"Location.Building":1}})
使用$push向数组中添加值
collection.update_many({"Location.Owner":"Anderson, Thomas"},{"$push":{"Tags":"Anderson"}})
使用$push和$each向数组中添加多个值
collection.update_one({"Location.Owner":re.compile("^Walker,")},{"$push":{'Tags':{'$each':['Walker','Warranty']}}})
使用$addToSet向现有数组中添加值
collection.update_many({"Type":"Chair"},{"$addToSet":{"Tags":"Warranty"}})
使用$pop从数组中删除元素
删除第一个元素
collection.update_one({"type":"Chair"},{"$pop":{"Tags":-1}})
删除最后一个元素
collection.update_one({"type":"Chair"},{"$pop":{"Tags":1}})
使用$pull删除特定的值(全部删除)
collection.update_one({"type":"Chair"},{"$pull":{"Tags":"Double"}})
使用replace_one()代替文档
collection.repalce_one(Desktop, NewDocument, upsert=True)
4)批处理数据
bulk = collection.initialize_ordered_bulk_op()
bulk.insert({"Type":"Laptop","ItemNumber":"2345EXD","Status":"Available"})
5)删除数据
删除文档
collection.delete_one({"Status":"In use"})
删除集合
db.items.drop()
删除数据库
c.drop_datebase("library")
6)在两个文档之间建立链接
在PyMongo中,数据库引用(DBRef)是通过DBRef模块中的DBRef()函数实现的,它可在处于不同位置的两个文档之间创建链接。
jan = {
"First Name" : "Jan",
"Last Name" : "Walker",
"Display name" : "Walker, Jan",
"Department" : "Development",
"Building" : "2B",
"Floor" : 12,
"Desk" : 120103,
"E-mail" : "jw@example.com"
}
people = db.people
people.insert(jan)
laptop = {
"Type" : "Laptop",
"Status" : "In use",
"ItemNumber" : "12345ABC",
"Tags" : ["Warranty","In use","Laptop"],
"Owner" : jan["_id"]
}
items = db.items
items.insert_one(laptop)
from bson.dbref import DBRef
mike = {
"First name" : "Mike",
"Last name" : "Wazowski",
"Display name" : "Wazowski, Mike",
"Department" : "Entertainment",
"Building" : "2B",
"Floor" : 10,
"Desk" : 120789,
"E-Mail" : "mw@monsters.inc"
}
people.insert_one(mike)
laptop = {
"Type" : "Laptop",
"Status" : "In use",
"ItemNumber" : "2345DEF",
"Tags" : ["Warranty","In use","Laptop"],
"Owner" : DBRef('people',mike["_id"])
}
items.insert_one(laptop)
person = items.find_one({"ItemNumber":"2345DEF"})
db.dereference(person["Owner"])
内容总结
以上是互联网集市为您收集整理的MongoDB学习笔记5——Python和MongoDB全部内容,希望文章能够帮你解决MongoDB学习笔记5——Python和MongoDB所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。