首页 后端开发 Python教程 Python中的MongoDB基本操作:连接、查询实例

Python中的MongoDB基本操作:连接、查询实例

Jun 10, 2016 pm 03:17 PM
mongodb python 基本操作 查询 连接

MongoDB是一个基于分布式文件存储的数据库。由C++语言编写。旨在为WEB应用提供可护展的高性能数据存储解决方案。它的特点是高性能、易部署、易使用,存储数据非常方便。

MongoDB 简单使用

联接数据库

复制代码 代码如下:

In [1]: import pymongo
In [2]: from pymongo import Connection
In [3]: connection = Connection('192.168.1.3', 27017) //创建联接

Connection 相关参数

复制代码 代码如下:

Connection([host='localhost'[, port=27017[, pool_size=None[, auto_start_request=None[, timeout=None[, slave_okay=False[, network_timeout=None[, document_class=dict[, tz_aware=True]]]]]]]]])

数据库操作

复制代码 代码如下:

In [9]: c.database_names() //列出所有数据库名称
Out[9]: [u'test', u'admin', u'yuhen', u'sms', u'local']

In [10]: c.server_info() //查看服务器相关信息
Out[10]:
{u'bits': 64,
 u'gitVersion': u'nogitversion',
 u'ok': 1.0,
 u'sysInfo': u'Linux yellow 2.6.24-27-server #1 SMP Fri Mar 12 01:23:09 UTC 2010 x86_64 BOOST_LIB_VERSION=1_40',
 u'version': u'1.2.2'}

In [16]: db = c['test'] //选择数据库
In [17]: db.collection_names() //列出当前数据库中所有集合名称
Out[17]: [u'system.indexes', u'fs.files', u'fs.chunks', u'test_gao']

In [23]: db.connection //查看联接信息
Out[23]: Connection('192.168.1.3', 27017)

In [24]: db.create_collection('test_abeen') //创建新集合
Out[24]: Collection(Database(Connection('192.168.1.3', 27017), u'test'), u'test_abeen')

In [25]: db.last_status() //查看上次操作状态
Out[25]: {u'err': None, u'n': 0, u'ok': 1.0}

In [26]: db.name //查看当前数据库名称
Out[26]: u'test'

In [27]: db.profiling_info() //查看配置信息
Out[27]: []

In [28]: db.profiling_level()
Out[28]: 0.0

集合操作

复制代码 代码如下:

In [31]: db.collection_names() //查看当前数据库所有集合名称
Out[31]:
[u'system.indexes',
 u'fs.files',
 u'fs.chunks',
 u'test_gao',
 u'system.users',
 u'test_abeen']

In [32]: c = db.test_abeen //选择集合
In [33]: c.name //查看当前集合名称
Out[33]: u'test_abeen'

In [35]: c.full_name //查看当前集合全名
Out[35]: u'test.test_abeen'
In [36]: c.database //查看当前集合数据库相关信息
Out[36]: Database(Connection('192.168.1.3', 27017), u'test')

In [38]: post = {"author":"Mike","text":"this is a test by abeen"}
In [39]: posts = db.posts
In [40]: posts.insert(post) //向数据库集合插入文档,默认创建集合
Out[40]: ObjectId('4c358492421aa91e70000000')
In [41]: db.collection_names() //显示所有集合名称
Out[41]:
[u'system.indexes',
 u'fs.files',
 u'fs.chunks',
 u'test_gao',
 u'system.users',
 u'test_abeen',
 u'posts']

In [42]: posts.find_one() //从集合查找信息
Out[42]:
{u'_id': ObjectId('4c358492421aa91e70000000'),
 u'author': u'Mike',
 u'text': u'this is a test by abeen'}
In [52]: p.update({"author":"Mike"},{"$set":{"author":"abeen","text":"this is a test by abeen shan shan"}})//更新集合文档信息
In [55]: list(p.find())
Out[55]:
[{u'_id': ObjectId('4c358492421aa91e70000000'),
  u'author': u'abeen',
  u'text': u'this is a test by abeen shan shan'}]

In [96]: list(posts.find())
Out[96]:
[{u'_id': ObjectId('4c358492421aa91e70000000'),
  u'author': u'Mike',
  u'text': u'this is a test by abeen'},
 {u'_id': ObjectId('4c358ad4421aa91e70000002'), u'a': u'aa', u'b': u'bb'},
 {u'_id': ObjectId('4c358ad9421aa91e70000003'), u'a': u'aa', u'b': u'bb'},
 {u'_id': ObjectId('4c358abb421aa91e70000001'),
  u'a': u'abeen',
  u'b': u'this bb is updated'}]
In [97]: posts.remove({"a":"abeen"}) //删除符合条件的文档
In [98]: list(posts.find())
Out[98]:
[{u'_id': ObjectId('4c358492421aa91e70000000'),
  u'author': u'Mike',
  u'text': u'this is a test by abeen'},
 {u'_id': ObjectId('4c358ad4421aa91e70000002'), u'a': u'aa', u'b': u'bb'},
 {u'_id': ObjectId('4c358ad9421aa91e70000003'), u'a': u'aa', u'b': u'bb'}]

In [102]: db.collection_names()
Out[102]:
[u'system.indexes',
 u'fs.files',
 u'fs.chunks',
 u'test_gao',
 u'system.users',
 u'test_abeen',
 u'posts',
 u'doc_abeen']

In [104]: db.drop_collection("doc_abeen") //删除集合
In [105]: db.collection_names()
Out[105]:
[u'system.indexes',
 u'fs.files',
 u'fs.chunks',
 u'test_gao',
 u'system.users',
 u'test_abeen',
 u'posts']

代码

复制代码 代码如下:

In [113]: result = db.posts.find({"a":"aa"})//查找
In [114]: type(result)
Out[114]:
In [119]: list(result)
Out[119]:
[{u'_id': ObjectId('4c358ad4421aa91e70000002'), u'a': u'aa', u'b': u'bb'},
 {u'_id': ObjectId('4c358ad9421aa91e70000003'), u'a': u'aa', u'b': u'bb'}]

find格式

复制代码 代码如下:

find([spec=None[, fields=None[, skip=0[, limit=0[, timeout=True[, snapshot=False[, tailable=False[, sort=None[, max_scan=None[, as_class=None[, **kwargs]]]]]]]]]]])

代码

复制代码 代码如下:

In [120]: db.posts.count()//当前集合文档数
Out[120]: 3
In [121]: type(db.posts)
Out[121]:

In [138]: posts.rename('test_abeen')//重命名当前集合
In [139]: db.collection_names()
Out[139]:
[u'system.indexes',
 u'fs.files',
 u'fs.chunks',
 u'test_gao',
 u'system.users',
 u'test_abeen']

In [151]: for post in c.find({"a":"aa"}).sort("a"): //查询并排序列
    post
Out[152]: {u'_id': ObjectId('4c358ad4421aa91e70000002'), u'a': u'aa', u'b': u'bb'}
Out[152]: {u'_id': ObjectId('4c358ad9421aa91e70000003'), u'a': u'aa', u'b': u'bb'}

复制代码 代码如下:

> db.foo.insert( { x : 1, y : 1 } )
> db.foo.insert( { x : 2, y : "string" } )
> db.foo.insert( { x : 3, y : null } )
> db.foo.insert( { x : 4 } )

// Query #1 y 为null或不存在
> db.foo.find( { "y" : null } )
{ "_id" : ObjectId("4dc1975312c677fc83b5629f"), "x" : 3, "y" : null }
{ "_id" : ObjectId("4dc1975a12c677fc83b562a0"), "x" : 4 }

// Query #2 y为null的值
> db.foo.find( { "y" : { $type : 10 } } )
{ "_id" : ObjectId("4dc1975312c677fc83b5629f"), "x" : 3, "y" : null }

// Query #3 y不存在的结果
> db.foo.find( { "y" : { $exists : false } } )
{ "_id" : ObjectId("4dc1975a12c677fc83b562a0"), "x" : 4 }

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
2 周前 By 尊渡假赌尊渡假赌尊渡假赌
仓库:如何复兴队友
1 个月前 By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒险:如何获得巨型种子
4 周前 By 尊渡假赌尊渡假赌尊渡假赌

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

Linux系统自带Python解释器能删除吗? Linux系统自带Python解释器能删除吗? Apr 02, 2025 am 07:00 AM

关于Linux系统自带Python解释器的删除问题许多Linux发行版在安装时会预装Python解释器,它并非通过软件包管理器�...

MongoDB在Debian上的高可用性如何保障 MongoDB在Debian上的高可用性如何保障 Apr 02, 2025 am 07:21 AM

本文介绍如何在Debian系统上构建高可用性的MongoDB数据库。我们将探讨多种方法,确保数据安全和服务持续运行。关键策略:副本集(ReplicaSet):利用副本集实现数据冗余和自动故障转移。当主节点出现故障时,副本集会自动选举新的主节点,保证服务的持续可用性。数据备份与恢复:定期使用mongodump命令进行数据库备份,并制定有效的恢复策略,以应对数据丢失风险。监控与报警:部署监控工具(如Prometheus、Grafana)实时监控MongoDB的运行状态,并

如何解决Python中自定义装饰器的Pylance类型检测问题? 如何解决Python中自定义装饰器的Pylance类型检测问题? Apr 02, 2025 am 06:42 AM

使用自定义装饰器时的Pylance类型检测问题解决方法在Python编程中,装饰器是一种强大的工具,可以用于添加行�...

Python 3.6加载pickle文件报错ModuleNotFoundError: No module named '__builtin__'怎么办? Python 3.6加载pickle文件报错ModuleNotFoundError: No module named '__builtin__'怎么办? Apr 02, 2025 am 06:27 AM

Python3.6环境下加载pickle文件报错:ModuleNotFoundError:Nomodulenamed...

在Linux终端中使用python --version命令时如何解决权限问题? 在Linux终端中使用python --version命令时如何解决权限问题? Apr 02, 2025 am 06:36 AM

Linux终端中使用python...

如何在Debian上配置MongoDB自动扩容 如何在Debian上配置MongoDB自动扩容 Apr 02, 2025 am 07:36 AM

本文介绍如何在Debian系统上配置MongoDB实现自动扩容,主要步骤包括MongoDB副本集的设置和磁盘空间监控。一、MongoDB安装首先,确保已在Debian系统上安装MongoDB。使用以下命令安装:sudoaptupdatesudoaptinstall-ymongodb-org二、配置MongoDB副本集MongoDB副本集确保高可用性和数据冗余,是实现自动扩容的基础。启动MongoDB服务:sudosystemctlstartmongodsudosys

如何在Python中通过信号杀死父进程后确保子进程也终止? 如何在Python中通过信号杀死父进程后确保子进程也终止? Apr 02, 2025 am 06:39 AM

使用信号杀死父进程时,子进程继续运行的问题及解决方案在Python编程中,通过信号杀死父进程后,子进程仍然...

See all articles