我应该如何在mongodb中存储布尔值? [英] How should I store boolean values in mongodb?

查看:1430
本文介绍了我应该如何在mongodb中存储布尔值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到在mongodb中存储布尔信息的三种主要可能性:

I see three main possibilities for storing boolean information in mongodb:

  1. 0或1作为字符串
  2. 0或1作为数字
  3. 布尔值为True或False

就使用的存储空间和查询速度而言,每种方法的优缺点是什么?

What are the advantages/disadvantages of each method in terms of storage space used and the speed of queries?

推荐答案

Boolean BSON ( MongoDB的服务器端存储格式,也称为二进制JSON").布尔运算使用的存储空间少于整数或字符串,并且避免了比较的任何意外副作用.

Boolean is a native field type in BSON (MongoDB's server-side storage format, aka "Binary JSON"). Booleans use less storage than an integer or string and avoid any unexpected side effects of comparison.

例如,在MongoDB find()查询中,字符串"1"与数字值1或布尔值true不匹配.如果要存储布尔值,请绝对使用布尔类型.

For example, in a MongoDB find() query a string of "1" will not match a numeric value of 1 or a boolean value of true. If you want to store boolean values, definitely use a boolean type.

比较mongo shell中的BSON大小(以字节为单位),以确保完整性:

Comparing the BSON size (in bytes) in the mongo shell for completeness:

// Number (JavaScript double) - 8 bytes
> var foo = { a: 1 }
> Object.bsonsize(foo)
16

// UTF-8 String - 6 bytes
> var foo = { a: '1'}
> Object.bsonsize(foo)
14

// 32-bit int - 4 bytes
> var foo = { a: NumberInt(1)}
> Object.bsonsize(foo)
12

// Boolean - 1 byte
> var foo = { a: true}
> Object.bsonsize(foo)
9

注意:上面示例中JSON对象的基本大小(不计算字段值)为8个字节,因此报告的Object.bsonsize()之间的差异是字段值的表示形式.

Note: the base size of the JSON object in the examples above (not counting the field values) is 8 bytes, so the difference between the reported Object.bsonsize() is the representation of the field value.

这篇关于我应该如何在mongodb中存储布尔值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆