#coding:utf-8
__author__ = 'hdfs'
import pymongo
from pymongo import MongoClient
client = MongoClient() client=MongoClient('10.0.0.9',27017)
#连接mongodb数据库
client = MongoClient('mongodb://10.0.0.9:27017/')
#指定数据库名称
db = client.test_database
#获取非系统的集合
db.collection_names(include_system_collections=False)
#获取集合名
posts = db.posts
#查找单个文档
posts.find_one()
#给定条件的一个文档
posts.find_one({"author": "Mike"})
#使用ID查找需要ObjectID
from bson.objectid import ObjectId
post_id='5728aaa96795e21b91c1aaf0'
document = client.db.collection.find_one({'_id': ObjectId(post_id)})
import datetime
new_posts = [{"author": "Mike",
"text": "Another post!",
"tags": ["bulk", "insert"],
"date": datetime.datetime(2009, 11, 12, 11, 14)},
{"author": "Eliot",
"title": "MongoDB is fun",
"text": "and pretty easy too!",
"date": datetime.datetime(2009, 11, 10, 10, 45)}]
#插入多条记录
result = posts.insert_many(new_posts)
#返回插入的ID
result.inserted_ids
#递归集合
for post in posts.find():
post #递归条件集合
for post in posts.find({"author": "Mike"}):
post #文档的记录数
posts.count() #区间查询
d = datetime.datetime(2009, 11, 12, 12)
for post in posts.find({"date": {"$lt": d}}).sort("author"):
print post
#给集合profiles建立索引 唯一索引
result = db.profiles.create_index([('user_id', pymongo.ASCENDING)],unique=True)
#查看索引信息
list(db.profiles.index_information())
#
user_profiles = [
{'user_id': 211, 'name': 'Luke'},
{'user_id': 212, 'name': 'Ziltoid'}]
result = db.profiles.insert_many(user_profiles) #聚合查询
from pymongo import MongoClient
db = MongoClient('mongodb://10.0.0.9:27017/').aggregation_example
#准备数据
result = db.things.insert_many([{"x": 1, "tags": ["dog", "cat"]},
{"x": 2, "tags": ["cat"]},
{"x": 2, "tags": ["mouse", "cat", "dog"]},
{"x": 3, "tags": []}])
result.inserted_ids
'''
{ "_id" : ObjectId("576aaa973e5269020848cc7c"), "x" : 1, "tags" : [ "dog", "cat" ] }
{ "_id" : ObjectId("576aaa973e5269020848cc7d"), "x" : 2, "tags" : [ "cat" ] }
{ "_id" : ObjectId("576aaa973e5269020848cc7e"), "x" : 2, "tags" : [ "mouse", "cat", "dog" ] }
{ "_id" : ObjectId("576aaa973e5269020848cc7f"), "x" : 3, "tags" : [ ] }
'''
from bson.son import SON
#$unwind 解开-后面的变量
pipeline = [
{"$unwind": "$tags"},
{"$group": {"_id": "$tags", "count": {"$sum": 1}}},
{"$sort": SON([("count", -1), ("_id", -1)])}
]
list(db.things.aggregate(pipeline))
#使用聚合函数with command
db.command('aggregate', 'things', pipeline=pipeline, explain=True)

  

python操作mongodb之基础操作的更多相关文章

  1. CentOS7安装MongoDB及基础操作

    安装环境说明 系统环境说明 [root@master ~]# cat /etc/redhat-release CentOS Linux release 7.4.1708 (Core) [root@ma ...

  2. python中文件的基础操作

    打开文件的三种方式: open(r'E:\学习日记\python\code\文件的简单操作.py') open('E:\\学习日记\\python\\code\\文件的简单操作.py') open(' ...

  3. PHP实现对MongoDB的基础操作

    PHP扩展                                                                                      PHP5.2.PH ...

  4. MongoDB数据库基础操作

    前面的话 为了保存网站的用户数据和业务数据,通常需要一个数据库.MongoDB和Node.js特别般配,因为Mongodb是基于文档的非关系型数据库,文档是按BSON(JSON的轻量化二进制格式)存储 ...

  5. Python学习---Django的基础操作180116

    Django创建数据库操作 django流程之model实例 settigs.py:更改Django2.0.1的配置,更新为之前的路径配置 'DIRS': [os.path.join(BASE_DIR ...

  6. MongoDB安装+基础操作

    MongoDB 一. 安装 这里展示使用docker安装mongoDB 拉取最新MongoDB镜像 docker pull mongo 运行容器 docker run -itd --name mong ...

  7. 使用 python 操作 mongodb 常用的操作

    pymongo 的安装命令 pip install pymongo. import pymongo 数据库及集合查询(创建) 连接数据库 查询数据库中的数据库 查询数据库中的集合 创建数据库和集合只需 ...

  8. python中字典的基础操作

    dict1 = { 'name':'王麻子', 'age':25, 'phone':12580, 'high':160 } dict2 = { 'name':'张三', 'age':38, 'phon ...

  9. JSP中的数据库操作,MySQL基础操作(一)

    一.JDBC JDBC(java data base concectivity),是一种用于执行SQL语句的java API,可以为多种关系库提供统一访问. 通常使用JDBC完成以下操作: 1)同数据 ...

随机推荐

  1. CentOS 安装Redis

    redis是当前比较热门的NOSQL系统之一,它是一个key-value存储系统.和Memcached类似,但很大程度补偿了memcached的不足,它支持存储的value类型相对更多,包括strin ...

  2. Tomcate配置单向双向SSL

    1.单向SSL 一.在Tomcate的service.xml文件中放开SSL配置 <!-- <Connector port="8443" protocol=" ...

  3. 编译android源码官方教程(4)开始编译

    Preparing to Build IN THIS DOCUMENT Obtain proprietary binaries Download proprietary binaries Extrac ...

  4. adb命令大全「含shell和wait-for-devices等」

    adb shell 大全: http://adbshell.com/commands 下列表格列出了adb常见命令,注意,它并不是只有adb shell,shell只是其中一个. Category C ...

  5. Python 2.7.9 Demo - isinstance

    #coding=utf-8 #!/usr/bin/python a = 'abc'; print isinstance(a, str);

  6. Struts2的输入校验(1)——校验规则文件的编写

    Struts2的输入校验(1) --校验规则文件的编写 Struts2提供了基于验证框架的输入校验,所有的输入校验只要编写配置文件,Struts2的验证框架将会负责进行服务器校验和客户端校验. 注: ...

  7. 详解CSS position属性

    原文地址:http://luopq.com/2015/11/15/css-position/ position是CSS中非常重要的一个属性,通过position属性,我们可以让元素相对于其正常位置,父 ...

  8. winfrom增删改查

    using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; usin ...

  9. HDU 4442 Physical Examination

    Physical Examination Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64 ...

  10. 【转载】C++内存分配

    原文:C++内存分配 内存泄露相信对C++程序员来说都不陌生.解决内存泄露的方案多种多样,大部分方案以追踪检测为主,这种方法实现起来容易,使用方便,也比较安全. 首先我们要确定这个模块的主要功能: 能 ...