Python操作mongodb方法(附源码)!

2018-09-18 06:42:13来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

MongoDB 是一个基于分布式文件存储的数据库,可以在高负载的情况下添加多个节点来承载压力,目前很多项目中用的也越来越多,这篇我们就介绍下如何用python操作mongodb数据库,从基本的安装说起,先熟练mongodb的基本操作,然后通过python实现数据插入、查询,以及mongoengine使用,最后是图形化界面连接mongodb数据库,我们从安装开始:

Mongodb 安装:

安装非常简单,直接下载安装包解压,就可以,步骤如下:

wget https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-rhel62-3.6.4.tgztar -zxvf mongodb-linux-x86_64-rhel62-3.6.4.tgzmv mongodb-linux-x86_64-rhel62-3.6.4 /usr/local/mongodb

 

然后添加系统环境变量,编辑/etc/profile文件加上如下行:

MONGODB=/usr/local/mongodbPATH=$MONGODB/bin:$PATHexport PATH

 

编辑mongodb配置文件,vi /etc/mongod.conf, 内容如下:

# mongod.conf# for documentation of all options, see:# http://docs.mongodb.org/manual/reference/configuration-options/# where to write logging data.systemLog: destination: file logAppend: true path: /var/log/mongodb/mongod.log# Where and how to store data.storage: dbPath: /var/lib/mongo journal: enabled: true# engine:# mmapv1:# wiredTiger:# how the process runsprocessManagement: fork: true # fork and run in background pidFilePath: /var/run/mongodb/mongod.pid # location of pidfile timeZoneInfo: /usr/share/zoneinfo# network interfacesnet: port: 27017 bindIp: 127.0.0.1,192.168.137.131 # Listen to local interface only, comment to listen on all interfaces.#security:#operationProfiling:#replication:#sharding:## Enterprise-Only Options#auditLog:#snmp:

 

创建数据库文件路径: mkdir -p /data/db

启动和关闭:

mongod & #启动mongod -shutdown -dbpath /data/db #关闭

 

另一个关闭方式:

登录数据库关闭:Mongo # 进入客户端use admin;db.shutdownServer();

上面就是mongodb的基本安装,启动和关闭操作,接下我们安装pymongo来看如何进行插入和查询数据:

pip install pymongo #先安装

实例1:插入一个对象

#coding=utf-8import datetimeimport pprintfrom pymongo import MongoClientclient = MongoClient()db = client.pythondbpost = {"_id": 100, "author": "Kuber", "text": "This is is my first post!", "tags": ["Docker", "Shell", "pymongo"], "date": datetime.datetime.utcnow()}posts = db.postspost_id = posts.insert_one(post).inserted_idprint("post_id is :", post_id)post = posts.find_one({"_id": post_id})print("Find By Post ID:")pprint.pprint(post)

 

实例2:插入多个对象:

#!/usr/bin/env python#coding=utf-8import datetimeimport pprintfrom pymongo import MongoClientclient = MongoClient()db = client.pythondbnew_posts = [{"_id": 1000, "author": "Curry", "text": "Another post!", "tags": ["bulk", "insert"], "date": datetime.datetime(2017, 11, 12, 11, 14)}, {"_id": 1001,"author": "Maxsu", "title": "MongoDB is fun", "text": "and pretty easy too!", "date": datetime.datetime(2019, 11, 10, 10, 45)}]posts = db.postsresult = posts.insert_many(new_posts)print("Bulk Inserts Result is :", result.inserted_ids)

 

实例3:数据查询

#!/usr/bin/env python #coding=utf-8 import datetime import pprint from pymongo import MongoClient client = MongoClient() db = client.pythondb posts = db.posts for post in posts.find(): pprint.pprint(post)

 

以上就是使用pymongo对数据库的插入和查询操作,这种方式可以实现很好的对mongodb的操作,但有时候我们经常用ORM进行数据库操作,尤其在使用django做项目时,那有没有类似的方法来操作mongodb呢,当时是有的,接下来我们来介绍下mongoengine, 通过mongoengine可以定义class来定义数据库表和字段,使用也不算复杂,而且它提供了大量的方法供我们使用,接下来看一个例子:

安装:pip install -U mongoengine

mongoengine实例1:

from mongoengine import *from datetime import datetimeconnect('test', host='localhost', port=27017)class Users(Document): name = StringField(required=True, max_length=200) age = IntField(required=True)class Categories(Document): name = StringField(max_length=30, required=True) artnum = IntField(default=0, required=True) date = DateTimeField(default=datetime.now(), required=True)class Posts(Document): title = StringField(max_length=100, required=True) content = StringField(required=True) tags = ListField(StringField(max_length=20, required=True), required=True) categories = ReferenceField(Categories)user1 = Users( name='zz', age= 11)user1.save() print(user1.name)user1.name = 'zz11'user1.save() print(user1.name)

 

如果熟悉ORM的小伙伴看上面代码会感觉很熟悉,这里就不多介绍了,然后看下查询用户的例子:

users = Users.objects.all()for u in users: print("name:",u.name,",age:", u.age)cate =Categories(name="Linux")cate.save()post = Posts(title="mindg.cn", content="mindg.cn",tags=["Linux","web"], categories=cate)post.save()cate = Posts.objects.all().first().categoriesprint cateprint cate.namecate = Categories.objects(name="Linux").first()print Posts.objects(categories=cate).next

 

以上就是简单的对mongodb的基本操作,下面我们说一下mongodb的可视化工具,虽然命令行显得比较高端一些,但图形化工具有时候跟他直观一些看到库里存储的内容,

操作mongo数据库用图形化还是很直观,我推荐用官网的Mongodb-compas:

图形化客户端连接:

Mongodb-compas下载

https://www.mongodb.com/download-center?jmp=hero#compass

下载安装后打开如图展示,是不是非常直观:

python操作mongodb方法(附源码)!

 

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:操作系统丶并发并行和线程

下一篇:实现统计 android手机 CPU使用率