from pymongo.mongo_client import MongoClient
client=MongoClient('192.168.30.252',27017)
client=drop_database('custom_type_example')
db=client.custom_type_example class Custom(object):
def __init__(self,x):
self.__x=x
def x(self):
return self.__x ###上面的类 不能自动编码 需要手动编码 如下
#将custom编码成json格式
def encode_custom(custom):
return {"_type": "custom", "x": custom.x()}
#将document还原成custom类
def decode_custom(document):
assert document["_type"] == "custom"
return Custom(document["x"])
db.test.insert({"custom": encode_custom(Custom(5))})
db.test.find_one()
decode_custom(db.test.find_one()["custom"])
decode_custom(db.test.find_one()["custom"]).x() foo=Custom(10)
foo.x() #手动显得繁琐,使用自动的吧
from pymongo.son_manipulator import SONManipulator
class Transform(SONManipulator):
def transform_incoming(self, son, collection):
for (key, value) in son.items():
if isinstance(value, Custom):
son[key] = encode_custom(value)
elif isinstance(value, dict): # Make sure we recurse into sub-docs
son[key] = self.transform_incoming(value, collection)
return son def transform_outgoing(self, son, collection):
for (key, value) in son.items():
if isinstance(value, dict):
if "_type" in value and value["_type"] == "custom":
son[key] = decode_custom(value)
else: # Again, make sure to recurse into sub-docs
son[key] = self.transform_outgoing(value, collection)
return son
#加入操纵者入数据库
db.add_son_manipulator(Transform())
#插入对象类型
db.test.insert({"custom": Custom(5)})
db.test.find_one()
#使用对象类型
db.test.find_one()["custom"].x()
5 def to_binary(custom):
return Binary(str(custom.x()), 128) def from_binary(binary):
return Custom(int(binary)) #二进制编码
from bson.binary import Binary
from pymongo.son_manipulator import SONManipulator
class TransformToBinary(SONManipulator):
def transform_incoming(self, son, collection):
for (key, value) in son.items():
if isinstance(value, Custom):
son[key] = to_binary(value)
elif isinstance(value, dict):
son[key] = self.transform_incoming(value, collection)
return son def transform_outgoing(self, son, collection):
for (key, value) in son.items():
if isinstance(value, Binary) and value.subtype == 128:
son[key] = from_binary(value)
elif isinstance(value, dict):
son[key] = self.transform_outgoing(value, collection)
return son
#加入二进制操作者
db.add_son_manipulator(TransformToBinary())

  

python操作mongodb之六自定义类型存储的更多相关文章

  1. python操作Redis安装、支持存储类型、普通连接、连接池

    一.python操作redis安装和支持存储类型 安装redis模块 pip3 install redis 二.Python操作Redis之普通连接 redis-py提供两个类Redis和Strict ...

  2. 使用Python操作MongoDB

    MongoDB简介(摘自:http://www.runoob.com/mongodb/mongodb-intro.html) MongoDB 由C++语言编写,是一个基于分布式文件存储的开源数据库系统 ...

  3. 第二百九十七节,python操作redis缓存-List类型,可以理解为列表

    python操作redis缓存-List类型,可以理解为列表,是可以有重复元素的列表 List操作,redis中的List在在内存中按照一个name对应一个List来存储.如图: lpush(name ...

  4. 【转】Python操作MongoDB

    Python 操作 MongoDB   请给作者点赞--> 原文链接 这篇文章主要介绍了使用Python脚本操作MongoDB的教程,MongoDB作为非关系型数据库得到了很大的宣传力度,而市面 ...

  5. Python操作MongoDB代码示例

    import pymongo #pip install pymongo安装python操作mongodb的模块 myclient=pymongo.MongoClient(host='127.0.0.1 ...

  6. Python 操作 mongodb 数据库

    原文地址:https://serholiu.com/python-mongodb 这几天在学习Python Web开发,于 是做准备做一个博客来练练手,当然,只是练手的,博客界有WordPress这样 ...

  7. python操作三大主流数据库(10)python操作mongodb数据库④mongodb新闻项目实战

    python操作mongodb数据库④mongodb新闻项目实战 参考文档:http://flask-mongoengine.readthedocs.io/en/latest/ 目录: [root@n ...

  8. MongoDB的安装与python操作MongoDB

    一.安装MongoDB 因为我个人使用的是windows,就只记录下windows下的安装 1.下载安装 就是官网,下载msi,选个路径安装 2.配置 看见别的地方说需要手动在bin同级目录创建dat ...

  9. 第二百九十五节,python操作redis缓存-字符串类型

    python操作redis缓存-字符串类型 首先要安装redis-py模块 python连接redis方式,有两种连接方式,一种是直接连接,一张是通过连接池连接 注意:以后我们都用的连接池方式连接,直 ...

随机推荐

  1. Java中的类加载器

    转载:http://blog.csdn.net/zhangjg_blog/article/details/16102131 从java的动态性到类加载机制   我们知道,Java是一种动态语言.那么怎 ...

  2. A fatal error has been detected by the Java Runtime Environment(jdk 1.6的一个BUG)

    几天做项目,生成一堆注解的实体,当实体数超过86个时,jvm报错: # # A fatal error has been detected by the Java Runtime Environmen ...

  3. hbase centOS生产环境配置笔记 (1 NameNode, 1 ResourceManager, 3 DataNode)

    本次是第一次在生产环境部署HBase,本文若有配置上的不妥之处还请高手指正. hadoop版本:hadoop-2.4.1 HBase版本:hbase-0.98.6.1-hadoop2 Zookeepe ...

  4. MVC 直接把数据库的数据输出到view(太神奇了)

    @model IEnumerable<MvcApplication32.Models.UserInfo> 后台是集合类型了 ,传到前台是model了,用 IEnumerable<&g ...

  5. 方法参数out

    using System;using System.Collections.Generic;using System.Linq;using System.Text; namespace _050505 ...

  6. 复旦大学2014--2015学年第一学期高等代数I期末考试情况分析

    一.期末考试成绩班级前几名 金羽佳(92).包振航(91).陈品翰(91).孙浩然(90).李卓凡(85).张钧瑞(84).郭昱君(84).董麒麟(84).张诚纯(84).叶瑜(84) 二.总成绩计算 ...

  7. 达人眼中的WINCE网络驱动

    实际上在WinCE上开发网络驱动,比如设计一个NIC驱动, 大多数情况,是从XP移植NDIS Miniport驱动(小端口驱动)到WinCE.什么是ndis?Ndis做什么用的? 什么是minipor ...

  8. MVC部署IIS设置

    根目录→处理程序映射→添加通配符脚本映射 C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll

  9. jquery之each()、$.each()[jQuery.each()]

    导航: 1,jQuery对象(实例)的each()函数 2,全局jQuery对象的each()函数 一:jQuery对象(实例)的each()函数 each()函数用于以当前jQuery对象匹配到的每 ...

  10. Django Models的数据类型

    Django中的页面管理后台 Djano中自带admin后台管理模块,可以通过web页面去管理,有点想php-admin,使用步骤: 在项目中models.py 中创建数据库表 class useri ...