我应该如何在 mongodb 中存储布尔值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27351143/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How should I store boolean values in mongodb?
提问by Chris Paterson
I see three main possibilities for storing boolean information in mongodb:
我看到在 mongodb 中存储布尔信息的三种主要可能性:
- 0 or 1 as a String
- 0 or 1 as a Number
- True or False as a Boolean
- 0 或 1 作为字符串
- 0 或 1 作为数字
- True 或 False 作为布尔值
What are the advantages/disadvantages of each method in terms of storage space used and the speed of queries?
每种方法在使用的存储空间和查询速度方面的优缺点是什么?
回答by Stennie
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.
Boolean
是BSON(MongoDB 的服务器端存储格式,又名“二进制 JSON”)中的原生字段类型。布尔值比整数或字符串使用更少的存储空间,并避免任何意外的比较副作用。
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.
例如,在 MongoDBfind()
查询中,字符串"1"
与 的数值1
或布尔值不匹配true
。如果要存储布尔值,请务必使用布尔类型。
Comparing the BSON size (in bytes) in the mongo
shell for completeness:
比较mongo
shell 中的 BSON 大小(以字节为单位)以确保完整性:
// 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
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.
注意:上述示例中JSON对象的基本大小(不包括字段值)为8个字节,因此报告的差异Object.bsonsize()
是字段值的表示形式。
回答by Shoham
If you have a couple of boolean values, than it might be fine to use BSON's built in boolean. But as seen below, each boolean's size is 4 bytes. So if your data is very small (compared to the extra 4 bytes), and/or you have many booleans, you might be better off using an integer bitmap with bitwiseoperations.
如果您有几个布尔值,那么使用 BSON 的内置布尔值可能会很好。但如下所示,每个布尔值的大小为 4 个字节。因此,如果您的数据非常小(与额外的 4 个字节相比),和/或您有很多布尔值,则最好使用带有按位运算的整数位图。
> var foo = {}
> Object.bsonsize(foo)
5
> foo.a = true
true
> Object.bsonsize(foo)
9
> foo.b = true
true
> Object.bsonsize(foo)
13