加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-17 01:01:23 所属栏目:Python 来源:网络整理
导读:MongoDB 是一个基于分布式文件存储的数据库,可以在高负载的情况下添加多个节点来承载压力,目前很多项目中用的也越来越多,这篇我们就介绍下如何用python操作mongodb数据库,从基本的安装说起,先熟练mongodb的基本操作,然后通过python实现数据插入、查询

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,14)},{"_id": 1001,"author": "Maxsu","title": "MongoDB is fun","text": "and pretty easy too!","date": datetime.datetime(2019,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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读