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

查看:320
本文介绍了在MongoDB中存储null与根本不存储密钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我看来,当您创建一个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. 根本不将密钥存储在该文档中
  1. Write {key: null} i.e. write null value in the field
  2. 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将检索您所有键为空不存在键的文档.

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屋!

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