英文:
How to subract the nested array object values in mongo
问题
你好,以下是翻译好的部分:
期望的输出:
差值:65-24 = 41
我尝试过这个:
{
$project: {
Difference: {
$subtract: ["$active.3.energy","$active.0.energy"]
}
}
}
查询2:
{
$project: {
Difference: {
$subtract: ["$active.$[n].energy","$active.0.energy"]
}
}
}
请注意,代码中的 $active
和 $active.$[n]
是 MongoDB 查询语言中的语法,表示引用文档中的字段。
英文:
I would like to know how to subtract the nested array object field values in mongodb.
{
Active: [
{min: 1, energy: 24},
{min: 2, energy: 34},
{min: 3, energy: 65}
]
}
Expected output:
Difference: 65-24 = 41
I have tried this:
{
$project: {
Difference: {
$subtract: ["$active.3.energy","$active.0.energy"]
}
}
}
query2:
{
$project: {
Difference: {
$subtract: ["$active.$[n].energy","$active.0.energy"]
}
}
}
答案1
得分: 0
这是一种你可以做到的方法。
db.collection.aggregate([
{
"$project": {
"Difference": {
"$subtract": [
{"$arrayElemAt": ["$Active.energy", 2]},
{"$arrayElemAt": ["$Active.energy", 0]}
]
}
}
}
])
在mongoplayground.net上尝试它。
英文:
Here's one way you could do it.
db.collection.aggregate([
{
"$project": {
"Difference": {
"$subtract": [
{"$arrayElemAt": ["$Active.energy", 2]},
{"$arrayElemAt": ["$Active.energy", 0]}
]
}
}
}
])
Try it on [mongoplayground.net](https://mongoplayground.net/p/XGcV17rdRTL "Click me!").
答案2
得分: 0
假设 Active
数组的长度可以任意,并且我们希望得到 energy
的最大值和最小值之间的差异。以下是一个解决方案:
db.foo.aggregate([
// 确保数组排序的顺序:
{$addFields: {
'Active': {$sortArray: {'input':'$Active', 'sortBy': { energy: 1 }}}
}}
// $arrayElemAt 是基于 0 的索引,所以需要 $size:'$Active' - 1:
,{$project: {
'difference': {$subtract: [
{$arrayElemAt:['$Active.energy', {$subtract:[{$size:'$Active'},1]} ]},
{$arrayElemAt:['$Active.energy',0]} ] }
}}
]);
英文:
Assume that the Active
array can be of arbitrary length and we wish to get the difference between the greatest and least value of energy
. Here's a solution:
db.foo.aggregate([
// Ensure sorted ordering of array:
{$addFields: {
'Active': {$sortArray: {'input':'$Active', 'sortBy': { energy: 1 }}}
}}
// $arrayElemAt is 0-based, so need $size:'$Active' - 1:
,{$project: {
'difference': {$subtract: [
{$arrayElemAt:['$Active.energy', {$subtract:[{$size:'$Active'},1]} ]},
{$arrayElemAt:['$Active.energy',0]} ] }
}}
]);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论