2022年 11月 16日

python中BSON模块使用详解

        下载PyMongo模块时 它会有一个相对应bson模块 也就是说 PyMongo模块的实现是基于和它一起的bson模块的
        该bson模块 并非我们用 pip install bson 安装的 bson。

        BSON是一种类json的一种二进制形式的存储格式,简称Binary JSON,它和JSON一样,支持内嵌的文档对象和数组对象,但是BSON有JSON没有的一些数据类型,如Date和BinData类型;
BSON有三个特点:轻量性、可遍历性、高效性,但是空间利用率不是很理想
MongoDB使用了BSON这种结构来存储数据和网络数据交换;

示例代码1:

  1. import bson
  2. json = {
  3. "title": "MongoDB",
  4. "last_editor": "192.168.1.122",
  5. "last_modified": "new Date('27/06/2011')",
  6. "body": "MongoDB introduction",
  7. "categories": ["Database", "NoSQL", "BSON"],
  8. "revieved": "false"
  9. }
  10. ret = bson.encode(json)
  11. print(ret)
  12. res = bson.decode(ret)
  13. print(res)

运行结果:

示例代码2:

  1. import bson
  2. json = {
  3. "name": "zhrb",
  4. "age": "25",
  5. "address": {
  6. "country": "china",
  7. "city": "bj",
  8. "code": 100000
  9. },
  10. "scores": [
  11. {"name": "english", "grade": 99},
  12. {"name": "chinese", "grade": 100}
  13. ]
  14. }
  15. ret = bson.encode(json)
  16. print(ret)
  17. res = bson.decode(ret)
  18. print(res)

运行结果:

示例代码3:

  1. import collections
  2. import bson
  3. from bson.codec_options import CodecOptions
  4. data = bson.BSON.encode({'a': 1})
  5. print(data)
  6. decoded_doc = bson.BSON.decode(data)
  7. print(decoded_doc)
  8. options = CodecOptions(document_class=collections.OrderedDict)
  9. print(options)
  10. decoded_doc = bson.BSON.decode(data, codec_options=options)
  11. print(type(decoded_doc))
  12. print(decoded_doc)

运行结果:

示例代码4:

  1. import collections
  2. import bson
  3. from bson.codec_options import CodecOptions
  4. data = {
  5. "name": "zhrb",
  6. "age": "25",
  7. "address": {
  8. "country": "china",
  9. "city": "bj",
  10. "code": 100000
  11. },
  12. "scores": [
  13. {"name": "english", "grade": 99},
  14. {"name": "chinese", "grade": 100}
  15. ]
  16. }
  17. data = bson.BSON.encode(data)
  18. print(data)
  19. decoded_doc = bson.BSON.decode(data)
  20. print(decoded_doc)
  21. options = CodecOptions(document_class=collections.OrderedDict)
  22. print(options)
  23. decoded_doc = bson.BSON.decode(data, codec_options=options)
  24. print(type(decoded_doc))
  25. print(decoded_doc)

运行结果:

参考博文:

BSON和JSON的区别_Reborn_Chang的博客-CSDN博客_bson和json区别

Python之读取MongoDB导出的BSON文件_山阴少年的博客-CSDN博客_bson文件

官方文档:bson – BSON (Binary JSON) Encoding and Decoding — PyMongo 3.4.0 documentation