如何在Mongo中减去嵌套数组对象的值

huangapple go评论64阅读模式
英文:

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]} ] }
    }}
]);

huangapple
  • 本文由 发表于 2023年5月11日 17:54:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/76226341.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定