如何一次從陣列中獲取滿足特定條件的多個元素,例如:Date <= 2020-12-31. 我讀過關于$elemMatch,但我只能得到一個特定的元素。
"someArray": [
{
"Date": "2021-09-30",
"value": "6.62"
},
{
"Date": "2020-12-31",
"value": "8.67"
},
{
"Date": "2019-12-31",
"value": "12.81"
},
{
"Date": "2018-12-31",
"value": "13.82"
},
{
"Date": "2017-12-31",
"value": "13.83"
},
...
]
uj5u.com熱心網友回復:
您可以$filter在這樣的聚合查詢中使用:
db.collection.aggregate([
{
"$project": {
"someArray": {
"$filter": {
"input": "$someArray",
"as": "a",
"cond": {
"$lte": [
"$$a.Date",
ISODate("2020-12-31")
]
}
}
}
}
}
])
示例在這里
請注意,您可以使用$project或$set(自 4.2 版起可用):example或$addFields: example
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/357800.html
標籤:MongoDB
下一篇:MongooseServerSelectionError:connectECONNREFUSED::1:27017innodev17andmongoisrunning
