必备专属
Python >= 3.2
six >= 1.10
mongodb >= 3.6
pymongo >= 3.6
mongoengine
一、安装mongodb,保证系统中安装了mongodb服务并启动,安装方法如下:
创建db存储目录(可自定)
md e:\mongodb\data
打开cmd并设置dbpath
"C:\Program Files\MongoDB\Server\3.6\bin\mongod.exe" --dbpath "e:\mongodb\data"
使用mongod.exe启动mongodb服务,主要打开database进程
"C:\Program Files\MongoDB\Server\3.6\bin\mongod.exe"
使用mongo.exe 连接mongodb数据库
三、安装pymongo
// pip安装
$ python -m pip install pymongo
// easy_install安装
$ python -m easy_install pymongo
// 下载git源安装
$ python setup.py install
test_connection.py
>>> import pymongo
>>> client = pymongo.MongoClient("localhost", 27017)
>>> db = client.test
>>> db.name
u'test'
>>> db.my_collection
Collection(Database(MongoClient('localhost', 27017), u'test'), u'my_collection')
>>> db.my_collection.insert_one({"x": 10}).inserted_id
ObjectId('4aba15ebe23f6b53b0000000')
>>> db.my_collection.insert_one({"x": 8}).inserted_id
ObjectId('4aba160ee23f6b543e000000')
>>> db.my_collection.insert_one({"x": 11}).inserted_id
ObjectId('4aba160ee23f6b543e000002')
>>> db.my_collection.find_one()
{u'x': 10, u'_id': ObjectId('4aba15ebe23f6b53b0000000')}
>>> for item in db.my_collection.find():
... print(item["x"])
...
三、安装mongoengine(通常django用此依赖操作mongodb)
pymongo来操作MongoDB数据库,但是直接把对于数据库的操作代码都写在脚本中,这会让应用的代码耦合性太强,而且不利于代码的优化管理
MongoEngine是一个对象文档映射器(ODM),相当于一个基于SQL的对象关系映射器(ORM)
MongoEngine提供的抽象是基于类的,创建的所有模型都是类
Examples:
from mongoengine import *
connect('test')
class BlogPost(Document):
title = StringField(required=True, max_length=200)
posted = DateTimeField(default=datetime.datetime.utcnow)
tags = ListField(StringField(max_length=50))
meta = {'allow_inheritance': True}
class TextPost(BlogPost):
content = StringField(required=True)
class LinkPost(BlogPost):
url = StringField(required=True)
# Create a text-based post
>>> post1 = TextPost(title='Using MongoEngine', content='See the tutorial')
>>> post1.tags = ['mongodb', 'mongoengine']
>>> post1.save()
# Create a link-based post
>>> post2 = LinkPost(title='MongoEngine Docs', url='hmarr.com/mongoengine')
>>> post2.tags = ['mongoengine', 'documentation']
>>> post2.save()