#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. python 数据加密以及生成token和token验证

    代码如下: # -*- coding: utf-8 -*- from passlib.apps import custom_app_context as pwd_context import conf ...

  2. 谈EXPORT_SYMBOL使用

    EXPORT_SYMBOL只出现在2.6内核中,在2.4内核默认的非static 函数和变量都会自动导入到kernel 空间的, 都不用EXPORT_SYMBOL() 做标记的.2.6就必须用EXPO ...

  3. git status message - Your branch is ahead of origin/master by X commits

    git reset --hard origin/master git status FAQ: When I issue the "git status" command, I se ...

  4. bzoj 2818: Gcd GCD(a,b) = 素数

    2818: Gcd Time Limit: 10 Sec  Memory Limit: 256 MBSubmit: 1566  Solved: 691[Submit][Status] Descript ...

  5. zoj Abs Problem

    Abs Problem Time Limit: 2 Seconds      Memory Limit: 65536 KB      Special Judge Alice and Bob is pl ...

  6. 2016 ACM/ICPC Asia Regional Qingdao Online HDU5883

    链接:http://acm.hdu.edu.cn/showproblem.php?pid=5883 解法:先判断是不是欧拉路,然后枚举 #pragma comment(linker, "/S ...

  7. 在Struts2中配置Action

    在Struts2中配置Action <package>: 1.定义Action使用<package>标签下的<action>标签完成,一个<package&g ...

  8. 【leetcode❤python】191. Number of 1 Bits

    #-*- coding: UTF-8 -*- class Solution(object):    def hammingWeight(self, n):        if n<=0:retu ...

  9. 4.mybatis属性和表的列名不相同时的处理方法

    /** * 属性和表的列名不相同时的处理方法 * 1.sql中给列重新命名: * select tid id, tname name from teacher t where tid=#{id} * ...

  10. Codeforces Round #382 (Div. 2) C. Tennis Championship 斐波那契

    C. Tennis Championship time limit per test 2 seconds memory limit per test 256 megabytes input stand ...