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

1,054 阅读2分钟

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

pymongo and mongoengine tutorial on ubuntu 16.04

Guide

version

  • 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 shell

    > 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 collections

    >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.

    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.

    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.

restart mongodb again

     > 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 now

    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