下载PyMongo模块时 它会有一个相对应bson模块 也就是说 PyMongo模块的实现是基于和它一起的bson模块的
该bson模块 并非我们用 pip install bson 安装的 bson。
BSON是一种类json的一种二进制形式的存储格式,简称Binary JSON,它和JSON一样,支持内嵌的文档对象和数组对象,但是BSON有JSON没有的一些数据类型,如Date和BinData类型;
BSON有三个特点:轻量性、可遍历性、高效性,但是空间利用率不是很理想
MongoDB使用了BSON这种结构来存储数据和网络数据交换;
示例代码1:
import bson
json = {
"title": "MongoDB",
"last_editor": "192.168.1.122",
"last_modified": "new Date('27/06/2011')",
"body": "MongoDB introduction",
"categories": ["Database", "NoSQL", "BSON"],
"revieved": "false"
}
ret = bson.encode(json)
print(ret)
res = bson.decode(ret)
print(res)
运行结果:
示例代码2:
import bson
json = {
"name": "zhrb",
"age": "25",
"address": {
"country": "china",
"city": "bj",
"code": 100000
},
"scores": [
{"name": "english", "grade": 99},
{"name": "chinese", "grade": 100}
]
}
ret = bson.encode(json)
print(ret)
res = bson.decode(ret)
print(res)
运行结果:
示例代码3:
import collections
import bson
from bson.codec_options import CodecOptions
data = bson.BSON.encode({'a': 1})
print(data)
decoded_doc = bson.BSON.decode(data)
print(decoded_doc)
options = CodecOptions(document_class=collections.OrderedDict)
print(options)
decoded_doc = bson.BSON.decode(data, codec_options=options)
print(type(decoded_doc))
print(decoded_doc)
运行结果:
示例代码4:
import collections
import bson
from bson.codec_options import CodecOptions
data = {
"name": "zhrb",
"age": "25",
"address": {
"country": "china",
"city": "bj",
"code": 100000
},
"scores": [
{"name": "english", "grade": 99},
{"name": "chinese", "grade": 100}
]
}
data = bson.BSON.encode(data)
print(data)
decoded_doc = bson.BSON.decode(data)
print(decoded_doc)
options = CodecOptions(document_class=collections.OrderedDict)
print(options)
decoded_doc = bson.BSON.decode(data, codec_options=options)
print(type(decoded_doc))
print(decoded_doc)
运行结果:
参考博文: