gpt4 book ai didi

mongodb - 特定领域和特定年份的平均数

转载 作者:行者123 更新时间:2023-12-03 02:48:38 25 4
gpt4 key购买 nike

我有这样的文件:

db.airportControl.insert({
identification: "21c3",
securityGateDate: new Date("2019-06-03T23:00:00Z"),
boardingDate: new Date("2019-06-03T23:40:00Z"),
gate: "A21",
airportDestiny: "LAX"
});
db.airportControl.insert({
identification: "21c3",
securityGateDate: new Date("2019-06-04T05:00:00Z"),
boardingDate: new Date("2018-06-04T05:21:00Z"),
gate: "A21",
airportDestiny: "LAX"
});
db.airportControl.insert({
identification: "21c3",
securityGateDate: new Date("2019-06-04T07:00:00Z"),
boardingDate: new Date("2018-06-04T07:41:00Z"),
gate: "A21",
airportDestiny: "LAX"
});
db.airportControl.insert({
identification: "21c3",
securityGateDate: new Date("2019-06-04T07:00:00Z"),
boardingDate: new Date("2019-06-04T07:41:00Z"),
gate: "A21",
airportDestiny: "TGU"
});

我想知道乘客从通过安检门到登机,按年份和机场在机场花费了多少时间

我有这个疑问。我得到了乘客在机场的平均花费。我如何才能在特定年份获得它们?例如 2019 年:

db.airportControl.aggregate([
{ $match: { airportDestiny: "LAX" } },
{
$group: {
_id: "",
average: { $avg: { $subtract: ["$boardingDate", "$securityGateDate"] } }
}
}
]);

最佳答案

您基本上请求两个结果,这可以通过使用两个查询或类似 $facet 的相同内容来实现。在这里。

db.collection.aggregate([
{ "$match": { "airportDestiny": "LAX" } },
{ "$facet": {
"totalAverage": [
{ "$group": {
"_id": null,
"average": {
"$avg": { "$subtract": ["$boardingDate", "$securityGateDate"] }
}
}}
],
"averageByYear": [
{ "$match": {
"$or": [
{ "$expr": { "$eq": [{ "$year": "$boardingDate" }, 2019] }},
{ "$expr": { "$eq": [{ "$year": "$securityGateDate" }, 2019]}}
]
}},
{ "$group": {
"_id": null,
"average": {
"$avg": { "$subtract": ["$boardingDate", "$securityGateDate"] }
}
}}
]
}}
])

更新:

db.collection.aggregate([
{ "$match": {
"airportDestiny": "LAX",
"$or": [
{ "$expr": { "$eq": [{ "$year": "$boardingDate" }, 2019] }},
{ "$expr": { "$eq": [{ "$year": "$securityGateDate" }, 2019] }}
]
}},
{ "$group": {
"_id": null,
"average": {
"$avg": { "$subtract": ["$boardingDate", "$securityGateDate"] }
}
}}
])

关于mongodb - 特定领域和特定年份的平均数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56464738/

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