我通過將一堆資料推送到陣列中來抓取并將其保存到 mongodb 集合中,已保存資料的示例如下所示:
{
"_id" : ObjectId("616eafce1e7edf6e9b033938"),
"collectibleId" : "34e05c2c-19dd-4509-a98c-bb11cd275d34",
"__v" : NumberInt(0),
"createdAt" : ISODate("2021-10-19T11:45:16.845 0000"),
"history" : [
{
"storePrice" : 6.99,
"value" : NumberInt(27),
"date" : ISODate("2021-10-19T11:45:16.683 0000"),
"totalListings" : NumberInt(904),
"hourlyChange" : {
"market" : NumberInt(0)
}
},
{
"storePrice" : 6.99,
"value" : 27.5,
"date" : ISODate("2021-10-19T11:59:01.192 0000"),
"totalListings" : NumberInt(902),
"hourlyChange" : {
"market" : NumberInt(0)
}
},
... loads more items ...
],
"updatedAt" : ISODate("2021-10-27T18:59:01.109 0000")
}
我現在正在嘗試為資料撰寫一個查詢,該查詢只能回傳特定時間范圍內的記錄資料。到目前為止,我已經嘗試過這個:
Prices.findOne({
collectibleId: slug,
history: {
date: {
$gte: new Date("2021-10-26T00:00:00.000Z")
}
}
}).exec((err, data) => {
if (err){
return res.status(400).json({
error: errorHandler(err)
})
}
res.json(data)
})
但我得到的結果總是空的。我想知道是不是因為日期嵌套在歷史中,也許我寫錯了?感謝您的任何建議。
uj5u.com熱心網友回復:
$match 然后 $set
db.collection.aggregate([
{
"$match": {
collectibleId: "slug",
"history.date": {
$gte: ISODate("2021-10-26T00:00:00.000Z")
}
}
},
{
"$set": {
"history": {
"$filter": {
"input": "$history",
"as": "h",
"cond": {
$gte: [
"$$h.date",
ISODate("2021-10-26T00:00:00.000Z")
]
}
}
}
}
}
])
mongoplayground
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/340248.html
