【发布时间】:2019-12-21 14:14:11
【问题描述】:
我在引用 $cond 语句中的嵌套数组项时遇到问题。
db.getCollection('bookings').aggregate([
{
$lookup: {
from: "listings",
localField: "listingId",
foreignField: "_id",
as: "listing"
}
},
{
$match: {
$and: [
{
locationId: ObjectId("5c0f0c882fcf07fb08890c27")
},
{
$or: [
{
$and: [
{
state: "booked"
},
{
startDate: {
$lte: new Date()
}
},
{
startDate: {
$gte: ISODate("2019-12-18T07:00:00.000Z")
}
}
]
},
{
$and: [
{
listing: {
$elemMatch: {
inspectionStatus: "none"
}
}
},
{
endDate: {
$lte: new Date()
}
},
{
endDate: {
$gte: ISODate("2019-12-18T07:00:00.000Z")
}
},
{
state: {
$in: [
"active",
"returned"
]
}
}
]
},
{
$and: [
{
state: {
$ne: "cancelled"
}
},
{
$or: [
{
$and: [
{
startDate: {
$gte: ISODate("2019-12-20T07:00:00.993Z")
}
},
{
startDate: {
$lte: ISODate("2019-12-21T06:59:59.999Z")
}
}
]
},
{
$and: [
{
endDate: {
$gte: ISODate("2019-12-20T07:00:00.993Z")
}
},
{
endDate: {
$lte: ISODate("2019-12-21T06:59:59.999Z")
}
}
]
}
]
}
]
}
]
}
]
}
},
{
$addFields: {
isLate: {
$cond: [
{
$or: [
{
$and: [
{
$eq: [
"$listing.0.inspectionStatus",
"none"
]
},
{
$lte: [
"$endDate",
new Date()
]
},
{
$gte: [
"$endDate",
ISODate("2019-12-18T07:00:00.000Z")
]
},
{
$in: [
"$state",
[
"active",
"returned"
]
]
},
]
},
{
$and: [
{
$eq: [
"$state",
"booked"
]
},
{
$lte: [
"$startDate",
new Date()
]
},
{
$gte: [
"$startDate",
ISODate("2019-12-18T07:00:00.000Z")
]
}
]
}
]
},
true,
false
]
}
}
}
])
在上面,$cond 语句中的以下几行根本不起作用:
$eq: [
"$listing.0.inspectionStatus",
"none"
]
我的问题是 - 我该如何进行上述工作?请注意,在查找之后,listing 字段中始终只有一个数组项(其中永远不会超过一个数组项)。我尝试了不同的变体,例如$listing.$0.$inspectionStatus - 但似乎没有任何效果。我可以沿着研究group 和filter 的轨迹走下去——但是当我只想访问listing 数组中的第一个也是唯一一个项目时,我觉得这有点过头了。
【问题讨论】:
-
请在jsoneditoronline.org分享输入和输出数据
-
@Mahesh output: jsoneditoronline.org/?id=bea99a897392432c8847d1ba2d2cb78a as for the input - 查看输出 -
listing是来自listing集合的列表文档,其余的输出只是一个文档bookings集合 -
请分享预订和列表
-
请告诉listingId键在哪里列出json
标签: mongodb mongoose mongodb-query aggregation-framework