【发布时间】:2021-06-21 05:24:57
【问题描述】:
我有许多名为“项目”的文件,格式如下:
Item = {
"_id" : ObjectId("6059f025fb8378a294180cc3"),
"name" : "My Name",
"category" : "My Category",
"marketData" : {
"currency" : "€",
"history" : [
{
"timestamp" : 1,
"price" : 1.1,
"volume" : 10
},
{
"timestamp" : 3,
"price" : 2.2,
"volume" : 20
},
]
}
}
历史长度不同,每个文档都有不同的时间戳,有些文档会共享几个时间戳。
我需要每个类别的每个时间戳的价格和数量的总和。 像这样:
Categories =
[{
"_id",
"name": "My Category",
"marketData": {
"currency": "€",
"history": [
{
"timestamp": 1,
"price": "sum of prices of all items at timestamp 1",
"volume": "sum of volume of all items at timestamp 1"
},
...
]
}
},
...
]
我已经试过了,但上面写着SyntaxError: invalid property id
db.items.aggregate([
{ $unwind: "$marketData.history" },
{
$group: {
_id: "$marketData.history.timestamp",
price: { $sum:"$marketData.history.price" }
},
{
$group: {
_id:null,
price: {
$push: { timestamp: "$timestamp", price:"$price" }
}
}
},
{
$project: {
marketData.history:1,
_id:0
}
}
}
])
【问题讨论】:
-
您期望的输出格式是什么?你的 MongoDB 版本是多少?
标签: mongodb mongoose aggregate