本文介绍了MongoDB“空"或NULL日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将开始在项目中使用MongoDB并进行以下观察: 日期"必须是有效的时间点,并且不能为NULL .

对于MongoDB,我们不能存储空日期,所以我猜测最好的办法是从文档中排除日期字段.

例如,如果我有一个汽车"文档和一个名为" date_sold "的字段.如果尚未出售汽车,则只需从文档中排除此字段即可.汽车售出后,我可以添加"date_sold"字段.

通过上述操作,我假设我可以查询已售或未售汽车的记录.这是在MongoDB中处理空"或空日期的推荐方法吗?

P.S.我感到困惑的原因是,由于SQL具有模式,所以日期或日期时间字段可以存储为NULL,但是在MongoDB中,日期"字段不能为NULL,并且必须是有效的时间点.

解决方案

在MongoDB中,没有日期存储时省略date字段可以正常工作,这不同于传统的SQL数据库,在传统的SQL数据库中,每个记录/文档都必须遵循相同的架构. /p>

您可以使用 $ exists 来测试值在那个领域.

I will begin using MongoDB in a project and made the following observation: ‘Date’ must be a valid point in time, and cannot be NULL.

With MongoDB, we cannot store a NULL date, so I am guessing that the best thing to do is to simply exclude the date field from our document.

For example, if I have a ‘car’ document and a field named ‘date_sold’. If the car has not been sold yet, I simply exclude this field from the document. Once the car sells, I can add the 'date_sold' field.

By doing the above, I am assuming that I can query records for cars sold or not sold. Is this a recommended way to handle "empty" or null dates in MongoDB?

P.S. My confusion stems from the fact that since SQL has a schema, date or datetime fields can be stored as NULL, but in MongoDB, a ‘Date’ field cannot be NULL and must be a valid point in time.

解决方案

Omitting the date field when there is no date to store works fine in MongoDB unlike a traditional SQL database where every record / document has to follow the same schema.

You can use $exists to test for a value in that field.

这篇关于MongoDB“空"或NULL日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 02:38