gpt4 book ai didi

mongodb - $cond 聚合中的嵌套条件

转载 作者:行者123 更新时间:2023-12-04 11:51:24 25 4
gpt4 key购买 nike

我正在尝试创建一个计算 状态 我的 Mongo 查询中的字段(状态:已创建、已收到付款、已发货、已收到、已完成)。

db.orders.aggregate( [
{ $project: { status: {
$cond: { if: { $ne: ["$feedback", null] },
then: 'finished', else: {
$cond: { if: { $ne: ["$received", null] },
then: 'received', else: {
$cond: { if: { $ne: ["$shipped", null] },
then: 'shipped', else: {
$cond: { if: { $ne: ["$payment", null] },
then: 'payment received', else: 'created' }
} }
} }
} }
} } },
{ $match: { } }
] )

示例数据:
{
"_id" : "xxxxxx0",
"payment" : ISODate("2016-02-03T10:45:00.011Z"),
"shipped" : ISODate("2016-02-03T11:55:00.011Z"),
"received" : ISODate("2016-02-03T12:45:00.011Z"),
"feedback" : ISODate("2016-02-03T14:34:00.011Z")
},
{
"_id" : "xxxxxx1",
"payment" : ISODate("2016-02-03T10:45:00.011Z"),
"shipped" : ISODate("2016-02-03T11:55:00.011Z"),
"received" : ISODate("2016-02-03T12:45:00.011Z")
},
{
"_id" : "xxxxxx2",
"payment" : ISODate("2016-02-03T10:45:00.011Z"),
"shipped" : ISODate("2016-02-03T11:55:00.011Z")
},
{
"_id" : "xxxxxx3",
"payment" : ISODate("2016-02-03T10:45:00.011Z")
},
{
"_id" : "xxxxxx4"
}

出于某种原因,我所有的结果都显示为“完成”,我使用 $cond 错了吗?它是否支持嵌套的 $cond ?

最佳答案

如果要检查该字段是否存在,则不能使用 $eq null,它将始终返回 true
有一个技巧可以用 $gt 做到这一点。您可以在此处查看完整说明 ( https://docs.mongodb.com/manual/reference/bson-types/#bson-types-comparison-order )

db.orders.aggregate( [
{ $project: { status: {
$cond: { if: { $gt: ["$feedback", null] },
then: 'finished', else: {
$cond: { if: { $gt: ["$received", null] },
then: 'received', else: {
$cond: { if: { $gt: ["$shipped", null] },
then: 'shipped', else: {
$cond: { if: { $gt: ["$payment", null] },
then: 'payment received', else: 'created' }
} }
} }
} }
} } },
{ $match: { } }
] )

关于mongodb - $cond 聚合中的嵌套条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38109312/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com