我正在使用具有以下结构的mongodb
{
"_id" : ObjectId("5a868d785e5436aeed0502c0"),
"symbol" : "ABC",
"values" : [
{
"High" : 53.0,
"Close" : 51.85,
"Open" : 50.8
},
{
"High" : 51.35,
"Close" : 50.25,
"Open" : 50.35
}
]
}
我想计算关闭字段的前2个元素的百分比变化。
但在计算差异时 collection.values [0] .Close - collection.values [1] .Close
我将priceiff作为null.PFB代码。
db.getCollection('abc').aggregate(
{
$project:
{
symbol:1,
today: { $arrayElemAt: [ "$values.Close", 0 ] },
yesterday: { $arrayElemAt: [ "$values.Close", 1 ] },
pricediff: {
$subtract: [ "$today", "$yesterday" ]
}
}})
还有其他方法来计算2个值的百分比变化。
感谢...,J
答案 0 :(得分:1)
任何新的(或重命名的)字段都不能在当前阶段使用,但仅限于后期阶段。
db.getCollection('abc').aggregate({
$project: {
symbol: 1,
today: {
$arrayElemAt: ["$values.Close", 0]
},
yesterday: {
$arrayElemAt: ["$values.Close", 1]
},
pricediff: {
// CAN NOT USE THESE FIELDS AS THEY WERE CREATED IN THIS
// PROJECTION
$subtract: ["$today", "$yesterday"]
}
}
})
由于新字段无法在创建它们的同一投影中使用,因此您可以使用多个阶段或重复代码来访问要计算值的字段。
db.getCollection('abc').aggregate([{
$project: {
symbol: 1,
today: {
$arrayElemAt: ["$values.Close", 0]
},
yesterday: {
$arrayElemAt: ["$values.Close", 1]
}
}
}, {
$project: {
symbol: 1,
today: 1,
yesterday: 1
pricediff: {
$subtract: ["$today", "$yesterday"]
}
}
}
}]);
$let
的单个投影阶段:db.getCollection('abc').aggregate([{
$project: {
symbol: 1,
today: {
$arrayElemAt: ["$values.Close", 0]
},
yesterday: {
$arrayElemAt: ["$values.Close", 1]
},
pricediff: {
$let: {
vars: {
today: {
$arrayElemAt: ["$values.Close", 0]
},
yesterday: {
$arrayElemAt: ["$values.Close", 1]
}
},
in: {
$subtract: ["$$today", "$$yesterday"]
}
}
}
}
}]);
db.getCollection('abc').aggregate([{
$project: {
symbol: 1,
today: {
$arrayElemAt: ["$values.Close", 0]
},
yesterday: {
$arrayElemAt: ["$values.Close", 1]
},
pricediff: {
$subtract: [
{ $arrayElemAt: ["$values.Close", 0] },
{ $arrayElemAt: ["$values.Close", 1] }
]
}
}
}]);
百分比变化只是以与计算差异相同的方式添加正确的公式。