Node.js 比较2个嵌入文档的特定字段后获取筛选的文档
我构建了一个列车时刻表集合,我想给出我的函数出发站和到达站,然后函数应该返回符合条件的列车 这是我收藏的一份文件Node.js 比较2个嵌入文档的特定字段后获取筛选的文档,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,我构建了一个列车时刻表集合,我想给出我的函数出发站和到达站,然后函数应该返回符合条件的列车 这是我收藏的一份文件 { "_id": 1, "train_id": 1, "train_type": "VIP", "stations": [ 1, 2, 3 ], "times": [ { "station_id": 1, "order": 1, "time": "05:00", "days": [
{
"_id": 1,
"train_id": 1,
"train_type": "VIP",
"stations": [
1,
2,
3
],
"times": [
{
"station_id": 1,
"order": 1,
"time": "05:00",
"days": [
"sun",
"mon",
"wed"
]
},
{
"station_id": 2,
"order": 2,
"time": "07:00",
"days": [
"sun",
"mon",
"thu",
"wed"
]
},
{
"station_id": 3,
"order": 3,
"time": "08:00",
"days": [
"sun",
"mon",
"thu"
]
}
]
}
所以我想让列车通过1号站和3号站,1号站的顺序应该比3号站的顺序低
使用普通的查找或聚合框架?您可以使用聚合框架来实现这一点。和将完成以下任务:
db.collection.aggregate([
{
$match : {"stations" : {$all : [1, 3]}} // This to make sure that the contains all the arrival and departure stations
},
{
"$addFields" : { // With this you'll get 2 new fields if the "$times" array contains them
"departureObject" : { $arrayElemAt: [ "$times", { $indexOfArray: [ "$times.station_id", 1 ] } ]},
"arrivalObject" : { $arrayElemAt: [ "$times", { $indexOfArray: [ "$times.station_id", 3 ] } ]}
}
},
{
$match: {$expr: {$gt: ["$arrivalObject.order", "$departureObject.order"]}} // This is to ensure that the arrival station is after departure station
}
]);
使用示例进行签出