MongoDB之一 hello world

使用python搭建一个学习mongoDB的环境
首先安装各种软件,包括mongoDB 3.4,python2.7,pymongo,bottle。

安装mongoDB 3.4

去官网下载msi的windows安装文件, 一路next安装完毕。
把安装路径下的D:\Program Files\MongoDB\Server\3.4\bin目录加到系统环境变量path里面。
命令行下启动monggoDB,先建立DB存储的目录如:c:\data\db

mongod --dbpath c:\data\db

把mongoDB做成系统服务
写一个配置文件 mongod.cfg

systemLog:
    destination: file
    path: 'c:\tmp\logs\mongod.log'
storage:
    dbPath: 'c:\data\db'

然后运行

mongod --config "c:\mongod.cfg" --install

服务建好了,用命令开启mongodb服务

net start mongoDB    --启动服务
net stop momgoDB   -- 停止服务

安装python 2.7

去官网下载2.7版本
https://www.python.org/downloads/
安装的时候把最后一项选上,目的是把Python27和它的Scripts目录加到系统环境变量的path。

MongoDB之一 hello world_第1张图片
image.png

安装 pymongo

pymongo是python操作mongoDB的模块(驱动)
https://api.mongodb.com/python/current/
安装, 命令行下

easy_install pymongo

安装 bottle

bottle是python下的一个非常简单易用的web框架
https://bottlepy.org/docs/dev/
安装

pip install bottle

好了准备工作就绪,可以愉快滴学习mongoDB了。
测试下效果:
在mongoDB的默认数据库test中插入2条数据,命令行下一行一行地敲如下代码:

mongo
db.user.save({'name':'tom', 'age':20})
db.user.save({'name':'jerry', 'age':21})
db.user.find()

在d盘建一个demo目录,新建一个hello.py

import pymongo 
import bottle 

@bottle.route('/')
def index():
    from pymongo import MongoClient
    client = MongoClient()
    db = client["test"]
    user = db.user
    item = user.find_one() 
    return  'hello %s!' % item['name']

bottle.run(host='localhost', port=8080)

然后执行

d:\demo> python hello.py

在浏览器中输入
http://localhost:8080

你可能感兴趣的:(MongoDB之一 hello world)