在字段上使用$ dateFromString时,避免结果中包含空字段 [英] Avoid having null fields in result when using $dateFromString on a field
本文介绍了在字段上使用$ dateFromString时,避免结果中包含空字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果某些文档中的字段为null,如何在字段上使用$ dateFromString时避免结果为空字段.
How to avoid having null fields in result when using $dateFromString on a field if the field is null in some documents.
Mongo Playground -结果中的日期字段不应为空
Mongo Playground - the result should not have any date fields with null
文档:
[
{
"date1": ISODate("2019-05-20T19:04:35.000Z")
},
{
"date1": ISODate("2019-05-20T19:04:35.000Z"),
"date2": ISODate("2019-05-20T19:04:35.000Z")
},
{
"date3": ISODate("2019-05-20T19:04:35.000Z")
}
]
预期:
[
{
"date1": ISODate("2019-05-20T00:00:00Z")
},
{
"date1": ISODate("2019-05-20T00:00:00Z"),
"date2": ISODate("2019-05-20T00:00:00Z")
},
{
"date3": ISODate("2019-05-20T00:00:00Z")
}
]
推荐答案
您可以使用 $ type
检查日期是否为空或缺少日期,如果缺少则请使用 $$ REMOVE
,
You can do it with checking if date is null or missing filed using $type
, if it is missing then remove using $$REMOVE
,
db.collection.aggregate([
{
$project: {
date1: {
$cond: {
if: {
$or: [
{ $eq: [{ $type: "$date1" }, "missing"] },
{ $eq: ["$date1", null] }
]
},
then: "$$REMOVE",
else: {
$dateFromString: {
dateString: {
$dateToString: {
format: "%Y-%m-%d",
date: "$date1"
}
}
}
}
}
},
date2: {
$cond: {
if: {
$or: [
{ $eq: [{ $type: "$date2" }, "missing"] },
{ $eq: ["$date2", null] }
]
},
then: "$$REMOVE",
else: {
$dateFromString: {
dateString: {
$dateToString: {
format: "%Y-%m-%d",
date: "$date2"
}
}
}
}
}
},
date3: {
$cond: {
if: {
$or: [
{ $eq: [{ $type: "$date3" }, "missing"] },
{ $eq: ["$date3", null] }
]
},
then: "$$REMOVE",
else: {
$dateFromString: {
dateString: {
$dateToString: {
format: "%Y-%m-%d",
date: "$date3"
}
}
}
}
}
}
}
}
])
这篇关于在字段上使用$ dateFromString时,避免结果中包含空字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文