java中的接口是类吗
293
2022-08-26
python操作MongoDB(python操作mongodb实验总结)
下载python中MongoDB的驱动程序
pip install pymongo
然后确保MongoDB已经安装且可以正常运行,去官网下载相应版本:-p /home/toolscd/home/toolswget -zxvf mongodb-linux-x86_64-3.4.2.tgzmv mongodb-linux-x86_64-3.4.2 mongodb3.4.2ln -s mongodb_3.4.2 mongodb
MongoDB 的可执行文件位于 bin 目录下,所以可以将其添加到 PATH 路径中
export PATH=/home/tools/mongodb/bin:$PATH
MongoDB的数据存储在data目录的db目录下,但是这个目录在安装过程不会自动创建,所以你需要手动创建data目录,并在data目录中创建db目录。
mkdir -p /data/db
在mongo安装目录中的bin目录执行mongod命令来启动mongdb服务
./mongod --dbpath /data/db
如果想进入MongoDB后台管理
./mongo
# ./mongoMongoDB shell version v3.4.2connecting to: mongodb://127.0.0.1:27017MongoDB server version: 3.4.2Welcome to the MongoDB shell......................times number of files.2017-03-12T01:15:04.901+0800 I CONTROL [initandlisten] >
使用用户 admin 使用密码 123456 连接到本地的 MongoDB 服务上
> mongodb://admin:123456@localhost/...
创建数据库(如果数据库不存在,则创建数据库,否则切换到指定数据库)
... use test2017-03-12T01:34:04.361+0800 E QUERY [thread1] SyntaxError: missing ; before statement @(shell):3:4
> use testswitched to db test> dbtest> show dbs #查看所有数据库admin 0.000GBlocal 0.000GB
python操作mongodb
连接mongodb
#!/usr/bin/env python# -*- coding:utf-8 -*-from pymongo import MongoClientconn = MongoClient('192.168.0.113', 27017)db = conn.mydb #连接mydb数据库,没有则自动创建my_set = db.test_set #使用test_set集合,没有则自动创建
插入数据(insert插入一个列表多条数据不用遍历,效率高, save需要遍历列表,一个个插入)
my_set.insert({"name":"zhangsan","age":18})#或my_set.save({"name":"zhangsan","age":18})
插入多条
#添加多条数据到集合中users=[{"name":"zhangsan","age":18},{"name":"lisi","age":20}] my_set.insert(users) #或my_set.save(users)
查询数据(查询不到则返回None)
#查询全部for i in my_set.find(): print(i)#查询name=zhangsan的for i in my_set.find({"name":"zhangsan"}): print(i)print(my_set.find_one({"name":"zhangsan"}))
更新数据
my_set.update(
把上面插入的数据内的age改为20
my_set.update({"name":"zhangsan"},{'$set':{"age":20}})
删除数据
my_set.remove(
#删除name=lisi的全部记录my_set.remove({'name': 'zhangsan'})#删除name=lisi的某个id的记录id = my_set.find_one({"name":"zhangsan"})["_id"]my_set.remove(id)#删除集合里的所有记录db.users.remove()
mongodb的条件操作符
# (>) 大于 - $gt# (<) 小于 - $lt# (>=) 大于等于 - $gte# (<= ) 小于等于 - $lte
#例:查询集合中age大于25的所有记录for i in my_set.find({"age":{"$gt":25}}): print(i)
type(判断类型)
#找出name的类型是String的for i in my_set.find({'name':{'$type':2}}): print(i)
类型队对照列表
排序
在MongoDB中使用sort()方法对数据进行排序,sort()方法可以通过参数指定排序的字段,并使用 1 和 -1 来指定排序的方式,其中 1 为升序,-1为降序。
for i in my_set.find().sort([("age",1)]): print(i)
limit和skip
#limit()方法用来读取指定数量的数据#skip()方法用来跳过指定数量的数据#下面表示跳过两条数据后读取6条for i in my_set.find().skip(2).limit(6): print(i)
IN
#找出age是20、30、35的数据for i in my_set.find({"age":{"$in":(20,30,35)}}): print(i)
OR
#找出age是20或35的记录for i in my_set.find({"$or":[{"age":20},{"age":35}]}): print(i)
all
'''dic = {"name":"lisi","age":18,"li":[1,2,3]}dic2 = {"name":"zhangsan","age":18,"li":[1,2,3,4,5,6]}my_set.insert(dic)my_set.insert(dic2)'''for i in my_set.find({'li':{'$all':[1,2,3,4]}}): print(i)#查看是否包含全部条件#输出:{'_id': ObjectId('58c503b94fc9d44624f7b108'), 'name': 'zhangsan', 'age': 18, 'li': [1, 2, 3, 4, 5, 6]}
push/pushAll
my_set.update({'name':"lisi"}, {'$push':{'li':4}})for i in my_set.find({'name':"lisi"}): print(i)#输出:{'li': [1, 2, 3, 4], '_id': ObjectId('58c50d784fc9d44ad8f2e803'), 'age': 18, 'name': 'lisi'}my_set.update({'name':"lisi"}, {'$pushAll':{'li':[4,5]}})for i in my_set.find({'name':"lisi"}): print(i)#输出:{'li': [1, 2, 3, 4, 4, 5], 'name': 'lisi', 'age': 18, '_id': ObjectId('58c50d784fc9d44ad8f2e803')}
pop/pull/pullAll
#pop#移除最后一个元素(-1为移除第一个)my_set.update({'name':"lisi"}, {'$pop':{'li':1}})for i in my_set.find({'name':"lisi"}): print(i)#输出:{'_id': ObjectId('58c50d784fc9d44ad8f2e803'), 'age': 18, 'name': 'lisi', 'li': [1, 2, 3, 4, 4]}#pull (按值移除)#移除3my_set.update({'name':"lisi"}, {'$pop':{'li':3}})#pullAll (移除全部符合条件的)my_set.update({'name':"lisi"}, {'$pullAll':{'li':[1,2,3]}})for i in my_set.find({'name':"lisi"}): print(i)#输出:{'name': 'lisi', '_id': ObjectId('58c50d784fc9d44ad8f2e803'), 'li': [4, 4], 'age': 18}
多级路径元素操作
先插入一条数据
dic = {"name":"zhangsan", "age":18, "contact" : { "email" : "1234567@qq.com", "iphone" : "11223344"} }my_set.insert(dic)
#多级目录用. 连接for i in my_set.find({"contact.iphone":"11223344"}): print(i)#输出:{'name': 'zhangsan', '_id': ObjectId('58c4f99c4fc9d42e0022c3b6'), 'age': 18, 'contact': {'email': '1234567@qq.com', 'iphone': '11223344'}}result = my_set.find_one({"contact.iphone":"11223344"})print(result["contact"]["email"])#输出:1234567@qq.com#多级路径下修改操作result = my_set.update({"contact.iphone":"11223344"},{"$set":{"contact.email":"9999999@qq.com"}})result1 = my_set.find_one({"contact.iphone":"11223344"})print(result1["contact"]["email"])#输出:9999999@qq.com
还可以对数组用索引操作
dic = {"name":"lisi", "age":18, "contact" : [ { "email" : "111111@qq.com", "iphone" : "111"}, { "email" : "222222@qq.com", "iphone" : "222"} ]}my_set.insert(dic)
#查询result1 = my_set.find_one({"contact.1.iphone":"222"})print(result1)#输出:{'age': 18, '_id': ObjectId('58c4ff574fc9d43844423db2'), 'name': 'lisi', 'contact': [{'iphone': '111', 'email': '111111@qq.com'}, {'iphone': '222', 'email': '222222@qq.com'}]}#修改result = my_set.update({"contact.1.iphone":"222"},{"$set":{"contact.1.email":"222222@qq.com"}})print(result1["contact"][1]["email"])#输出:222222@qq.com
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 from pymongo import MongoClient 4 5 settings = { 6 "ip":'192.168.0.113', #ip 7 "port":27017, #端口 8 "db_name" : "mydb", #数据库名字 9 "set_name" : "test_set" #集合名字10 }11 12 class MyMongoDB(object):13 def __init__(self):14 try:15 self.conn = MongoClient(settings["ip"], settings["port"])16 except Exception as e:17 print(e)18 self.db = self.conn[settings["db_name"]]19 self.my_set = self.db[settings["set_name"]]20 21 def insert(self,dic):22 print("inser...")23 self.my_set.insert(dic)24 25 def update(self,dic,newdic):26 print("update...")27 self.my_set.update(dic,newdic)28 29 def delete(self,dic):30 print("delete...")31 self.my_set.remove(dic)32 33 def dbfind(self,dic):34 print("find...")35 data = self.my_set.find(dic)36 for result in data:37 print(result["name"],result["age"])38 39 def main():40 dic={"name":"zhangsan","age":18}41 mongo = MyMongoDB()42 mongo.insert(dic)43 mongo.dbfind({"name":"zhangsan"})44 45 mongo.update({"name":"zhangsan"},{"$set":{"age":"25"}})46 mongo.dbfind({"name":"zhangsan"})47 48 mongo.delete({"name":"zhangsan"})49 mongo.dbfind({"name":"zhangsan"})50 51 if __name__ == "__main__":52 main()
下载python中MongoDB的驱动程序
pip install pymongo
然后确保MongoDB已经安装且可以正常运行,去官网下载相应版本:-p /home/toolscd/home/toolswget -zxvf mongodb-linux-x86_64-3.4.2.tgzmv mongodb-linux-x86_64-3.4.2 mongodb3.4.2ln -s mongodb_3.4.2 mongodb
MongoDB 的可执行文件位于 bin 目录下,所以可以将其添加到 PATH 路径中
export PATH=/home/tools/mongodb/bin:$PATH
MongoDB的数据存储在data目录的db目录下,但是这个目录在安装过程不会自动创建,所以你需要手动创建data目录,并在data目录中创建db目录。
mkdir -p /data/db
在mongo安装目录中的bin目录执行mongod命令来启动mongdb服务
./mongod --dbpath /data/db
如果想进入MongoDB后台管理
./mongo
# ./mongoMongoDB shell version v3.4.2connecting to: mongodb://127.0.0.1:27017MongoDB server version: 3.4.2Welcome to the MongoDB shell......................times number of files.2017-03-12T01:15:04.901+0800 I CONTROL [initandlisten] >
使用用户 admin 使用密码 123456 连接到本地的 MongoDB 服务上
> mongodb://admin:123456@localhost/...
创建数据库(如果数据库不存在,则创建数据库,否则切换到指定数据库)
... use test2017-03-12T01:34:04.361+0800 E QUERY [thread1] SyntaxError: missing ; before statement @(shell):3:4
> use testswitched to db test> dbtest> show dbs #查看所有数据库admin 0.000GBlocal 0.000GB
python操作mongodb
连接mongodb
#!/usr/bin/env python# -*- coding:utf-8 -*-from pymongo import MongoClientconn = MongoClient('192.168.0.113', 27017)db = conn.mydb #连接mydb数据库,没有则自动创建my_set = db.test_set #使用test_set集合,没有则自动创建
插入数据(insert插入一个列表多条数据不用遍历,效率高, save需要遍历列表,一个个插入)
my_set.insert({"name":"zhangsan","age":18})#或my_set.save({"name":"zhangsan","age":18})
插入多条
#添加多条数据到集合中users=[{"name":"zhangsan","age":18},{"name":"lisi","age":20}] my_set.insert(users) #或my_set.save(users)
查询数据(查询不到则返回None)
#查询全部for i in my_set.find(): print(i)#查询name=zhangsan的for i in my_set.find({"name":"zhangsan"}): print(i)print(my_set.find_one({"name":"zhangsan"}))
更新数据
my_set.update(
把上面插入的数据内的age改为20
my_set.update({"name":"zhangsan"},{'$set':{"age":20}})
删除数据
my_set.remove(
#删除name=lisi的全部记录my_set.remove({'name': 'zhangsan'})#删除name=lisi的某个id的记录id = my_set.find_one({"name":"zhangsan"})["_id"]my_set.remove(id)#删除集合里的所有记录db.users.remove()
mongodb的条件操作符
# (>) 大于 - $gt# (<) 小于 - $lt# (>=) 大于等于 - $gte# (<= ) 小于等于 - $lte
#例:查询集合中age大于25的所有记录for i in my_set.find({"age":{"$gt":25}}): print(i)
type(判断类型)
#找出name的类型是String的for i in my_set.find({'name':{'$type':2}}): print(i)
类型队对照列表
排序
在MongoDB中使用sort()方法对数据进行排序,sort()方法可以通过参数指定排序的字段,并使用 1 和 -1 来指定排序的方式,其中 1 为升序,-1为降序。
for i in my_set.find().sort([("age",1)]): print(i)
limit和skip
#limit()方法用来读取指定数量的数据#skip()方法用来跳过指定数量的数据#下面表示跳过两条数据后读取6条for i in my_set.find().skip(2).limit(6): print(i)
IN
#找出age是20、30、35的数据for i in my_set.find({"age":{"$in":(20,30,35)}}): print(i)
OR
#找出age是20或35的记录for i in my_set.find({"$or":[{"age":20},{"age":35}]}): print(i)
all
'''dic = {"name":"lisi","age":18,"li":[1,2,3]}dic2 = {"name":"zhangsan","age":18,"li":[1,2,3,4,5,6]}my_set.insert(dic)my_set.insert(dic2)'''for i in my_set.find({'li':{'$all':[1,2,3,4]}}): print(i)#查看是否包含全部条件#输出:{'_id': ObjectId('58c503b94fc9d44624f7b108'), 'name': 'zhangsan', 'age': 18, 'li': [1, 2, 3, 4, 5, 6]}
push/pushAll
my_set.update({'name':"lisi"}, {'$push':{'li':4}})for i in my_set.find({'name':"lisi"}): print(i)#输出:{'li': [1, 2, 3, 4], '_id': ObjectId('58c50d784fc9d44ad8f2e803'), 'age': 18, 'name': 'lisi'}my_set.update({'name':"lisi"}, {'$pushAll':{'li':[4,5]}})for i in my_set.find({'name':"lisi"}): print(i)#输出:{'li': [1, 2, 3, 4, 4, 5], 'name': 'lisi', 'age': 18, '_id': ObjectId('58c50d784fc9d44ad8f2e803')}
pop/pull/pullAll
#pop#移除最后一个元素(-1为移除第一个)my_set.update({'name':"lisi"}, {'$pop':{'li':1}})for i in my_set.find({'name':"lisi"}): print(i)#输出:{'_id': ObjectId('58c50d784fc9d44ad8f2e803'), 'age': 18, 'name': 'lisi', 'li': [1, 2, 3, 4, 4]}#pull (按值移除)#移除3my_set.update({'name':"lisi"}, {'$pop':{'li':3}})#pullAll (移除全部符合条件的)my_set.update({'name':"lisi"}, {'$pullAll':{'li':[1,2,3]}})for i in my_set.find({'name':"lisi"}): print(i)#输出:{'name': 'lisi', '_id': ObjectId('58c50d784fc9d44ad8f2e803'), 'li': [4, 4], 'age': 18}
多级路径元素操作
先插入一条数据
dic = {"name":"zhangsan", "age":18, "contact" : { "email" : "1234567@qq.com", "iphone" : "11223344"} }my_set.insert(dic)
#多级目录用. 连接for i in my_set.find({"contact.iphone":"11223344"}): print(i)#输出:{'name': 'zhangsan', '_id': ObjectId('58c4f99c4fc9d42e0022c3b6'), 'age': 18, 'contact': {'email': '1234567@qq.com', 'iphone': '11223344'}}result = my_set.find_one({"contact.iphone":"11223344"})print(result["contact"]["email"])#输出:1234567@qq.com#多级路径下修改操作result = my_set.update({"contact.iphone":"11223344"},{"$set":{"contact.email":"9999999@qq.com"}})result1 = my_set.find_one({"contact.iphone":"11223344"})print(result1["contact"]["email"])#输出:9999999@qq.com
还可以对数组用索引操作
dic = {"name":"lisi", "age":18, "contact" : [ { "email" : "111111@qq.com", "iphone" : "111"}, { "email" : "222222@qq.com", "iphone" : "222"} ]}my_set.insert(dic)
#查询result1 = my_set.find_one({"contact.1.iphone":"222"})print(result1)#输出:{'age': 18, '_id': ObjectId('58c4ff574fc9d43844423db2'), 'name': 'lisi', 'contact': [{'iphone': '111', 'email': '111111@qq.com'}, {'iphone': '222', 'email': '222222@qq.com'}]}#修改result = my_set.update({"contact.1.iphone":"222"},{"$set":{"contact.1.email":"222222@qq.com"}})print(result1["contact"][1]["email"])#输出:222222@qq.com
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 from pymongo import MongoClient 4 5 settings = { 6 "ip":'192.168.0.113', #ip 7 "port":27017, #端口 8 "db_name" : "mydb", #数据库名字 9 "set_name" : "test_set" #集合名字10 }11 12 class MyMongoDB(object):13 def __init__(self):14 try:15 self.conn = MongoClient(settings["ip"], settings["port"])16 except Exception as e:17 print(e)18 self.db = self.conn[settings["db_name"]]19 self.my_set = self.db[settings["set_name"]]20 21 def insert(self,dic):22 print("inser...")23 self.my_set.insert(dic)24 25 def update(self,dic,newdic):26 print("update...")27 self.my_set.update(dic,newdic)28 29 def delete(self,dic):30 print("delete...")31 self.my_set.remove(dic)32 33 def dbfind(self,dic):34 print("find...")35 data = self.my_set.find(dic)36 for result in data:37 print(result["name"],result["age"])38 39 def main():40 dic={"name":"zhangsan","age":18}41 mongo = MyMongoDB()42 mongo.insert(dic)43 mongo.dbfind({"name":"zhangsan"})44 45 mongo.update({"name":"zhangsan"},{"$set":{"age":"25"}})46 mongo.dbfind({"name":"zhangsan"})47 48 mongo.delete({"name":"zhangsan"})49 mongo.dbfind({"name":"zhangsan"})50 51 if __name__ == "__main__":52 main()
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~