pymongo和mongoengine安装和使用教程 包含经常使用命令行和代码示例 | pymongo and mongoengine tutorial on ubuntu 16.04

本文首发于我的博客kezunlin.me/post/e88f04…,欢迎阅读最新内容!html

pymongo and mongoengine tutorial on ubuntu 16.04node

Guide

versionpython

  • mongo 2.6.10
  • mongo gui: robo3t-1.3.1
  • pymongo 3.9.0
  • MongoEngine 0.18.2

install mongodb

sudo apt-get install -y mongodb复制代码

mongo shell

mongo --host mongodb0.example.com --port 27017复制代码
mongo --version
    MongoDB shell version: 2.6.10复制代码

see mongo shelllinux

> mongo 
    # show all dbs
    > show dbs复制代码
# display current db
    >db
    test (default database)复制代码
# switch or create db
    > use mydb
    > db.help()复制代码
> show collections
    posts
    system.indexes复制代码
> db.posts.help()复制代码
> db.posts.find()复制代码

help on db and collectionsmongodb

>db.dropDatabase()
    >db.posts.drop()
    >db.copyDatabase("mydb","backup_mydb")
   复制代码

mongo gui

Robomongo offically changed it's name and released two different products Studio 3T and Robo 3T. Old robomongo is now called Robo 3T. Studio 3T is for professionals.shell

wget https://download-test.robomongo.org/linux/robo3t-1.3.1-linux-x86_64-7419c406.tar.gz复制代码
vim .bashrc
    export PATH=/home/kezunlin/program/robo3t/bin:$PATH复制代码

allow mongodb to access from remote.ubuntu

vim /etc/mongodb.conf
    #bind_ip = 127.0.0.1
    bind_ip = 0.0.0.0复制代码

by default, mongodb only allow to access from local.vim

restart mongodb againbash

> sudo service mongodb status
     mongodb.service - An object/document-oriented database
       Loaded: loaded (/lib/systemd/system/mongodb.service; enabled; vendor preset: enabled)
       Active: active (running) since 四 2019-09-26 16:11:03 CST; 7s ago
         Docs: man:mongod(1)
     Main PID: 4917 (mongod)
        Tasks: 10
       Memory: 3.0G
          CPU: 70ms
       CGroup: /system.slice/mongodb.service
               └─4917 /usr/bin/mongod --config /etc/mongodb.conf复制代码
9月 26 16:11:03 node17 systemd[1]: Started An object/document-oriented database.
    9月 26 16:11:03 node17 mongod[4917]: warning: bind_ip of 0.0.0.0 is unnecessary; listens on all ips by default
 复制代码

access from remote nowapp

robo3t复制代码

python mongodb

pip install pymongo
    pip install mongoengine复制代码

One library that provides a higher abstraction on top of PyMongo is MongoEngine. MongoEngine is an object document mapper (ODM), which is roughly equivalent to a SQL-based object relational mapper (ORM). The abstraction provided by MongoEngine is class-based, so all of the models you create are classes.

pymongo

def test_mongo_client():

    from pymongo import MongoClient
    client = MongoClient('localhost', 27017)

    db = client['mydb']

    posts = db.posts
    post_data = {
        'title': 'Python and MongoDB',
        'content': 'PyMongo is fun, you guys',
        'author': 'Scott'
    }
    result = posts.insert_one(post_data)
    print('One post: {0}'.format(result.inserted_id))


    post_1 = {
        'title': 'Python and MongoDB',
        'content': 'PyMongo is fun, you guys',
        'author': 'Scott'
    }
    post_2 = {
        'title': 'Virtual Environments',
        'content': 'Use virtual environments, you guys',
        'author': 'Scott'
    }
    post_3 = {
        'title': 'Learning Python',
        'content': 'Learn Python, it is easy',
        'author': 'Bill'
    }
    new_result = posts.insert_many([post_1, post_2, post_3])
    print('Multiple posts: {0}'.format(new_result.inserted_ids))

    # find one 
    bills_post = posts.find_one({'author': 'Bill'})
    print(bills_post)

    # fine many
    scotts_posts = posts.find({'author': 'Scott'})
    print(scotts_posts)

    for post in scotts_posts:
        print(post)

    client.close()
复制代码

mongoengine

from mongoengine import *

def test_mongo_engine():
    # define collection 
    class Post(Document):
        title = StringField(required=True, max_length=200)
        content = StringField(required=True)
        author = StringField(required=True, max_length=50)
        published = DateTimeField(default=datetime.datetime.now)

    connect('mydb', 
        host='localhost', 
        port=27017, 
        alias="default" # must be `default`
    )
    # mongoengine.connection.MongoEngineConnectionError: You have not defined a default connection

    post_1 = Post(
        title='Sample Post',
        content='Some engaging content',
        author='Scott'
    )
    post_1.save()       # This will perform an insert
    print(post_1.title)
    print(post_1.id)

    post_1.title = 'A Better Post Title'
    post_1.save()       # This will perform an atomic edit on "title"
    print(post_1.title)
    print(post_1.id)

    disconnect(alias='default')

test_mongo_engine()复制代码

Reference

History

  • 20190926: created

Copyright

相关文章
相关标签/搜索