简体   繁体   English

MongoDB文档:空值还是省略对?

[英]MongoDB documents: empty value or omit pair altogether?

I'm using MongoDB for the first time on a project, and I'm not quite sure what is the recommended approach for blank/unset values in a document. 我在项目中第一次使用MongoDB,我不太确定文档中空白/未设置值的推荐方法是什么。 Which of these two approaches is more appropriate when you have pairs that will likely have values in the future: 当您拥有将来可能具有值的对时,这两种方法中的哪一种更合适:

1) The JSON where the description field is an empty string (and will be populated in the future): 1)JSON,其中description字段是一个空字符串(并将在以后填充):

{
    "username": "jamies",
    "shortName": "camping",
    "setName": "Camping on Stevens",
    "description": ""
}

2) Or, the JSON where the description field is omitted (and will be added in the future): 2)或者,省略描述字段的JSON(将来会添加):

{
    "username": "jamies",
    "shortName": "camping",
    "setName": "Camping on Stevens"
}

Obviously the 2nd approach will save disk space, but also doesn't indicate what values are null. 显然,第二种方法将节省磁盘空间,但也不会指示哪些值为null。 I'd love to understand which is recommended/prescribed by Mongo developers/DBAs, and if there are any considerations with that approach during query or update. 我很想了解Mongo开发人员/ DBA推荐/规定的内容,以及在查询或更新期间是否考虑过该方法。

When in doubt 有疑问时

Start with brevity. 从简洁开始。 Increase the other dimensions as required by testing. 根据测试要求增加其他尺寸。 jeff-atwood 杰夫·阿特伍德

The quote above refers to code, but it applies here, as well. 上面的引用是指代码,但它也适用于此处。 I can think of a few situations where you'll regret adding an empty string field in the future. 我可以想到一些情况,你会后悔在将来添加一个空字符串字段。 eg. 例如。 Deprecating the field, it not being in use anymore, confusing people, and just taking up space. 弃用该领域,它不再被使用,令人困惑,只是占用空间。 Also, refer to MongoDB Docs: Querying and nulls . 另请参阅MongoDB Docs:查询和空值

One way is to ignore the fields that are not applicable for the document/aggregate under question. 一种方法是忽略不适用于所讨论的文档/聚合的字段。 Document data bases like MongoDB are schema less and support this natively. 像MongoDB这样的文档数据库是模式较少的,并且原生支持它。 You can then use the $exists query operator. 然后,您可以使用$ exists查询运算符。 But if your use-case is heavy on the queries that depend upon exists then it is non-performant and alternate designs are mentioned . 但是,如果您的用例在依赖于存在的查询上很重,那么它就是非高效的并且提到了替代设计

Another way is to use null to indicate the absence of a value. 另一种方法是使用null来表示缺少值。 I think using null is suggested instead of adding a element and providing empty string as the value. 我认为建议使用null而不是添加元素并提供空字符串作为值。 Somewhat similar discussion here XML, what is this: null or empty element? 这里有点类似的讨论XML,这是什么:null或空元素?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM