我的檔案看起來像:
[
{
value: 'Apple',
createdAt: '2021-12-09T20:15:26.421 00:00',
},
{
value: 'Blueberry',
createdAt: '2021-12-09T20:45:26.421 00:00',
},
{
value: 'Cranberry',
createdAt: '2021-12-09T21:30:26.421 00:00',
},
{
value: 'Durian',
createdAt: '2022-01-24T20:15:26.421 00:00',
},
{
value: 'Elderberry',
createdAt: '2022-01-24T20:45:26.421 00:00',
},
]
我想做一個聚合,我得到最舊的檔案,但需要注意的是,如果一個小時內創建了另一個檔案,它會使第一個檔案無效,我實際上想抓住那個檔案。例如,在上面我想回傳Cranberry. 最初選擇Apple,但由于Blueberry在一小時內到達,移動到那個,并且因為Cranberry在 的一小時內到達Blueberry,選擇Cranberry。
uj5u.com熱心網友回復:
您可以在聚合管道中執行以下操作:
$sort經過createdAt$limit獲取最舊的檔案$lookup獲取createdAt當前檔案后面的所有檔案$reduce回圈結果陣列;僅當當前條目在 1 小時內時才更新累加器/結果
db.collection.aggregate([
{
$sort: {
createdAt: 1
}
},
{
$limit: 1
},
{
"$lookup": {
"from": "collection",
let: {
current: "$createdAt"
},
pipeline: [
{
$match: {
$expr: {
$gte: [
"$createdAt",
"$$current"
]
}
}
}
],
"as": "within"
}
},
{
"$addFields": {
"within": {
"$reduce": {
"input": "$within",
"initialValue": null,
"in": {
"$cond": {
"if": {
$or: [
{
$eq: [
"$$value",
null
]
},
{
$lte: [
{
"$subtract": [
"$$this.createdAt",
"$$value.createdAt"
]
},
3600000
]
}
]
},
"then": "$$this",
"else": "$$value"
}
}
}
}
}
}
])
這是Mongo游樂場供您參考。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/429517.html
標籤:mongodb 猫鼬 mongodb查询 聚合框架 nosql-聚合
