四时宝库

程序员的知识宝库

Python数据库(三)MongoDB基本使用

安装

pip install pymongo

导入

from pymongo import MongoClient

连接MongoDB Server

client = MongoClient('localhost', 27017)

列出所有数据库

client.list_database_names()

创建/选择数据库

如果post_db不存在,则自动新建此数据库。

post_db = client.get_database('post_db')

列出库内所有的集合

post_db.list_collection_names()

新建/选择集合

如果post_collection不存在,则新建此集合。

post_collection = post_db.get_collection('post_collection')

插入一条文档

import datetime
post = {"author": 'zhangsan', 'text': '我的第一篇博客', "tags": ['mongodb', 'python', 'pymongo'],
        "date": datetime.datetime.utcnow()}
post_collection.insert_one(post)

查询单条文档

post_collection.find_one()

插入多条文档

list = [{'author': 'lisi', "text": 'lisi text'}, {'author': 'wangwu', 'text': 'wangwu text'}]
post_collection.insert_many(list)

遍历集合内的文档

for i in post_collection.find():
    print(i)



发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言
    友情链接