如何在 mongodb 查询中的 if 条件下检查空数组?
How to check empty array in if condition in mongodb query?
我试图通过编写以下 mongodb 带有 if else 条件的投影查询来确定数组是否为空。
[
'$project' => [
'_id' => 1.0,
'Name' => 1.0,
'AllotmentsDetails' => 1.0,
'NonExpiredAllotmentsOfRoomWithCheckoutZero' => 1.0,
'NonExpiredAllotmentsOfRoomWithCheckoutOne' => 1.0,
'NonExpiredAllotmentsOfRoom' => 1.0,
'RecentAllotmentsDetails' => [
'$cond'=> [
'if'=> [
'$not' => ['$NonExpiredAllotmentsOfRoom' => [ '$size' => 0 ]]
],
'then' => ['$arrayElemAt' => ['$NonExpiredAllotmentsOfRoom', -1 ]],
'else' => []
]
]
]]
基本上我正在尝试检查“$NonExpiredAllotmentsOfRoom”是否为空。如果它是空的,它应该 return 空数组否则它应该 return '$NonExpiredAllotmentsOfRoom' 的最后一个元素。上面的代码抛出错误消息 "Unrecognized expression '$NonExpiredAllotmentsOfRoom"。请帮忙 !!!
RecentAllotmentsDetails => {
$cond: { if: { $ne: [
"$NonExpiredAllotmentsOfRoom", [] ] },
then: ['$arrayElemAt' =>
['$NonExpiredAllotmentsOfRoom', -1 ]] ,
else: []
}
}
在您的管道中试试这个
我试图通过编写以下 mongodb 带有 if else 条件的投影查询来确定数组是否为空。
[
'$project' => [
'_id' => 1.0,
'Name' => 1.0,
'AllotmentsDetails' => 1.0,
'NonExpiredAllotmentsOfRoomWithCheckoutZero' => 1.0,
'NonExpiredAllotmentsOfRoomWithCheckoutOne' => 1.0,
'NonExpiredAllotmentsOfRoom' => 1.0,
'RecentAllotmentsDetails' => [
'$cond'=> [
'if'=> [
'$not' => ['$NonExpiredAllotmentsOfRoom' => [ '$size' => 0 ]]
],
'then' => ['$arrayElemAt' => ['$NonExpiredAllotmentsOfRoom', -1 ]],
'else' => []
]
]
]]
基本上我正在尝试检查“$NonExpiredAllotmentsOfRoom”是否为空。如果它是空的,它应该 return 空数组否则它应该 return '$NonExpiredAllotmentsOfRoom' 的最后一个元素。上面的代码抛出错误消息 "Unrecognized expression '$NonExpiredAllotmentsOfRoom"。请帮忙 !!!
RecentAllotmentsDetails => {
$cond: { if: { $ne: [
"$NonExpiredAllotmentsOfRoom", [] ] },
then: ['$arrayElemAt' =>
['$NonExpiredAllotmentsOfRoom', -1 ]] ,
else: []
}
}
在您的管道中试试这个