Pymongo tutorial (3) Custom Data Types

Source: Internet
Author: User
Pymongo provides some common data types, such as data, strings, and dates. If you still cannot meet your requirements, you can customize the data type. First, define a class: classCustom (object): def _ init _ (self, x): self. _ xxdefx (self): returnself. _ x

Pymongo provides some common data types, such as data, strings, and dates. If you still cannot meet your requirements, you can customize the data type. First, define a class: class Custom (object): def _ init _ (self, x): self. _ x = x def x (self): return self. _ x

Pymongo provides some common data types, such as data, strings, and dates. If you still cannot meet your requirements, you can customize the data type.

First, define a class:

class Custom(object):    def __init__(self, x):        self.__x = x    def x(self):        return self.__x

Encoding is required before storing custom data into the database. decoding is required after the data is read from the database.

Manual encoding/Decoding

We can define two methods for manual encoding and decoding during data insertion and query.

def encode_custom(custom):    return {"_type": "custom", "x": custom.x()}def decode_custom(document):    assert document["_type"] == "custom"    return Custom(document["x"])print(db.test.insert({"custom": encode_custom(Custom(5))}))print(db.test.find_one()['custom'])
Automatic encoding/Decoding

Manual encoding is feasible, but not convenient. We can also use SONManipulator for automatic encoding.

from pymongo.son_manipulator import SONManipulatorclass 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 sondb.add_son_manipulator(Transform())print(db.test.insert({"custom": Custom(5)}))print(db.test.find_one())
Binary encoding

We can also encode it into binary for storage.

from bson.binary import Binarydef to_binary(custom):    return Binary(str(custom.x()), 128)def from_binary(binary):    return Custom(int(binary))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 sondb.add_son_manipulator(TransformToBinary())print(db.test.insert({"custom": Custom(5)}))print(db.test.find_one())

Original article address: pymongo tutorial (3) -- custom data type, thanks to the original author for sharing.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.