pymongo和mongoengine安装和使用教程 包含常用命令行和代码示例

pymongo和mongoengine安装和使用教程 包含常用命令行和代码示例本文首发于个人博客https://kezunlin.me/post/e88f04e5/,欢迎阅读最新内容! pymongo and mongoengine tutorial on ubuntu 16…

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

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

代码100分

mongo shell

代码100分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

代码100分>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

<script async src=”https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js”></script>

<!– kzl in-article ad –>

<ins class=”adsbygoogle” style=”display:block; text-align:center;” data-ad-layout=”in-article” data-ad-format=”fluid” data-ad-client=”ca-pub-5653382914441020″ data-ad-slot=”7925631830″></ins>

<script> (adsbygoogle = window.adsbygoogle || []).push({}); </script>

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

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
转载请注明出处: https://daima100.com/10558.html

(0)
上一篇 2022-12-25
下一篇 2022-12-25

相关推荐

  • 如何退出conda

    如何退出condaConda是一个包管理系统和环境管理系统。它可以让你在不同的项目之间快速切换环境,并管理不同的依赖包。Conda也提供了一些命令行工具,包括conda、conda-env和conda-build等工具,用于在conda环境下进行不同的操作。

    2024-09-01
    19
  • 数据库未来发展趋势(上)

    数据库未来发展趋势(上)数据库是IT技术栈中承上启下的关键一层,具有如下特性: 向上承托应用开发与运行,是应用生态关键组成之一。 向下对接硬件和OS,对数据处理应用屏蔽底层硬件复杂性和兼容性。 数据库系统是IT技术栈中的独…

    2023-04-13
    149
  • Python 中如何反转字符串?

    Python 字符串是 Unicode 字符的集合。Python 有很多字符串操作的函数,但是 Python 字符串库不支持内置的“reverse()”函数。但是有各种方法来反转弦。我们正在定义以下方法来反转 Python 字符串。

    2023-08-24
    129
  • 解决SQL SERVER 2012自增ID突然断开的问题(ID突然增加1000的)

    解决SQL SERVER 2012自增ID突然断开的问题(ID突然增加1000的)最近这两年创建数据库的自增Id列总是出现一个问题,一开始自增正常,都是1、2、3递增,突然就变成1004、1005这样,一直以为程序有问题,后来多次查阅资料才在国外网站上找到问题。

    2023-02-10
    144
  • Python yieldfrom:简化异步编程的利器

    Python yieldfrom:简化异步编程的利器随着计算机技术和通信技术的不断发展,异步编程的需求越来越大。异步编程可以提高程序的并发性,从而提升程序的性能和响应速度。但异步编程对程序可读性和可维护性提出了更高的要求,因为异步编程需要处理大量的回调和状态管理。

    2024-07-13
    45
  • SqlServer性能优化,查看CPU、内存占用大的会话及SQL语句[通俗易懂]

    SqlServer性能优化,查看CPU、内存占用大的会话及SQL语句[通俗易懂]1,查看CPU占用量最高的会话及SQL语句 select spid,cmd,cpu,physical_io,memusage, (select top 1 [text] from ::fn_get_s

    2022-12-22
    144
  • 50个SQL语句(MySQL版) 问题六[通俗易懂]

    50个SQL语句(MySQL版) 问题六[通俗易懂]表结构 student(StuId,StuName,StuAge,StuSex) 学生表 teacher(TId,Tname) 教师表 course(CId,Cname,C_TId) 课程表 sc(S

    2023-02-26
    149
  • 荣耀30s性价比如何_荣耀20颜色识图

    荣耀30s性价比如何_荣耀20颜色识图     今天带大家来了解一下我个人十分喜欢的荣耀30S。荣耀30S是今年荣耀的开年5G诚意之作,首发超强性能麒麟820 5G SoC,拥有高颜值的同时还配备6400W高清四摄和40W快充等的强劲功…

    2023-02-19
    148

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注