在 MongoDB 中存储 null 与根本不存储密钥 [英] Storing null vs not storing the key at all in MongoDB
问题描述
在我看来,当您创建 Mongo 文档并有一个字段 {key: value}
有时不会有值时,您有两个选择:
It seems to me that when you are creating a Mongo document and have a field {key: value}
which is sometimes not going to have a value, you have two options:
- 写入
{key: null}
即在字段中写入 null 值 - 根本不要将密钥存储在该文档中
- Write
{key: null}
i.e. write null value in the field - Don't store the key in that document at all
这两个选项都很容易查询,一个是查询 {key : null}
,另一个是查询 {key : {$exists : false}}
.
Both options are easily queryable, in one you query for {key : null}
and the other you query for {key : {$exists : false}}
.
我真的想不出这两个选项之间有什么区别会对应用场景产生任何影响(除了选项 2 的存储空间稍少).
I can't really think of any differences between the two options that would have any impact in an application scenario (except that option 2 has slightly less storage).
谁能告诉我是否有任何理由让人们更喜欢这两种方法中的任何一种,为什么?
Can anyone tell me if there are any reasons one would prefer either of the two approaches over the other, and why?
编辑
在问了这个问题后,我还想到索引在这两种情况下的行为可能不同,即可以为选项 2 创建一个稀疏索引.
After asking the question it also occurred to me that indexes may behave differently in the two cases i.e. a sparse index can be created for option 2.
推荐答案
其实你还有第三种可能:key: ""
(空值)
Indeed you have also a third possibility :
key: ""
(empty value)
你忘记了关于空值的特殊性.查询key: null
将检索所有 key 为 null 或的文档,其中 key 不存在.
And you forget a specificity about null value.
Query on
key: null
will retrieve you all document where key is null or where key doesn't exist.
当对 $exists:false
的查询将只检索字段键不存在的文档.
When a query on $exists:false
will retrieve only doc where field key doesn't exist.
要回到您的确切问题,这取决于您的查询和数据代表的内容.如果您需要保留它,例如,用户设置了一个值然后取消设置它,您应该将该字段保留为 null 或空.如果您不需要,您可以删除此字段.
To go back to your exact question it depends of you queries and what data represent. If you need to keep that, by example, a user set a value then unset it, you should keep the field as null or empty. If you dont need, you may remove this field.
这篇关于在 MongoDB 中存储 null 与根本不存储密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!