在 MongoDB 中存储空值与根本不存储密钥 [英] Storing null vs not storing the key at all in MongoDB

查看:18
本文介绍了在 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:

  1. {key: null} 即在字段中写空值
  2. 根本不要将密钥存储在该文档中

这两个选项都很容易查询,一个是查询 {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 中存储空值与根本不存储密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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