下面的聚合由MongoDB 5支持,但不支持4.4。我如何用v4.4来写这个呢?
聚集管道(V5):
"$ifNull": [
{
"$getField": {
"field": "prices",
"input": {
"$first": "$matchedUsers"
}
}
},
[]
]这是一个相同的MongoDB游乐场。
发布于 2022-09-14 17:01:33
这个管道应该在4.4版本中工作:
db.datasets.aggregate([
{
"$lookup": {
"from": "users",
"localField": "assignedTo",
"foreignField": "id",
"as": "matchedUsers"
}
},
{
"$addFields": {
"cgData": {
"$first": "$matchedUsers"
}
}
},
{
"$addFields": {
"cgData": {
"$first": {
"$filter": {
"input": {
"$ifNull": [
"$cgData.prices",
[]
]
},
"as": "currentPrice",
"cond": {
"$and": [
{
"$gte": [
"$firstBillable",
"$$currentPrice.beginDate"
]
},
{
$or: [
{
$eq: [
{
$type: "$$currentPrice.endDate"
},
"missing"
]
},
{
"$lt": [
"$firstBillable",
"$$currentPrice.endDate"
]
}
]
}
]
}
}
}
}
}
},
{
"$addFields": {
cgPrice: "$cgData.price"
}
},
{
"$project": {
cgData: 0,
"matchedUsers": 0
}
}
])在此中,增加了一个新的$addFields阶段,以获得matchedUsers数组的第一个元素。
{
"$addFields": {
"cgData": {
"$first": "$matchedUsers"
}
}
}然后我们像这样使用$ifNull:
{
"$ifNull": [
"$cgData.prices",
[]
]
}看到它在运行这里。
https://stackoverflow.com/questions/73717420
复制相似问题