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

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

How to subract the nested array object values in mongo

问题

你好,以下是翻译好的部分:

期望的输出:
差值:65-24 = 41

我尝试过这个:

  1. {
  2. $project: {
  3. Difference: {
  4. $subtract: ["$active.3.energy","$active.0.energy"]
  5. }
  6. }
  7. }

查询2:

  1. {
  2. $project: {
  3. Difference: {
  4. $subtract: ["$active.$[n].energy","$active.0.energy"]
  5. }
  6. }
  7. }

请注意,代码中的 $active$active.$[n] 是 MongoDB 查询语言中的语法,表示引用文档中的字段。

英文:

I would like to know how to subtract the nested array object field values in mongodb.

  1. {
  2. Active: [
  3. {min: 1, energy: 24},
  4. {min: 2, energy: 34},
  5. {min: 3, energy: 65}
  6. ]
  7. }

Expected output:
Difference: 65-24 = 41

I have tried this:

  1. {
  2. $project: {
  3. Difference: {
  4. $subtract: ["$active.3.energy","$active.0.energy"]
  5. }
  6. }
  7. }

query2:

  1. {
  2. $project: {
  3. Difference: {
  4. $subtract: ["$active.$[n].energy","$active.0.energy"]
  5. }
  6. }
  7. }

答案1

得分: 0

这是一种你可以做到的方法。

  1. db.collection.aggregate([
  2. {
  3. "$project": {
  4. "Difference": {
  5. "$subtract": [
  6. {"$arrayElemAt": ["$Active.energy", 2]},
  7. {"$arrayElemAt": ["$Active.energy", 0]}
  8. ]
  9. }
  10. }
  11. }
  12. ])

mongoplayground.net上尝试它。

英文:

Here's one way you could do it.

  1. db.collection.aggregate([
  2. {
  3. "$project": {
  4. "Difference": {
  5. "$subtract": [
  6. {"$arrayElemAt": ["$Active.energy", 2]},
  7. {"$arrayElemAt": ["$Active.energy", 0]}
  8. ]
  9. }
  10. }
  11. }
  12. ])

Try it on [mongoplayground.net](https://mongoplayground.net/p/XGcV17rdRTL "Click me!").

答案2

得分: 0

假设 Active 数组的长度可以任意,并且我们希望得到 energy 的最大值和最小值之间的差异。以下是一个解决方案:

  1. db.foo.aggregate([
  2. // 确保数组排序的顺序:
  3. {$addFields: {
  4. 'Active': {$sortArray: {'input':'$Active', 'sortBy': { energy: 1 }}}
  5. }}
  6. // $arrayElemAt 是基于 0 的索引,所以需要 $size:'$Active' - 1:
  7. ,{$project: {
  8. 'difference': {$subtract: [
  9. {$arrayElemAt:['$Active.energy', {$subtract:[{$size:'$Active'},1]} ]},
  10. {$arrayElemAt:['$Active.energy',0]} ] }
  11. }}
  12. ]);
英文:

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:

  1. db.foo.aggregate([
  2. // Ensure sorted ordering of array:
  3. {$addFields: {
  4. 'Active': {$sortArray: {'input':'$Active', 'sortBy': { energy: 1 }}}
  5. }}
  6. // $arrayElemAt is 0-based, so need $size:'$Active' - 1:
  7. ,{$project: {
  8. 'difference': {$subtract: [
  9. {$arrayElemAt:['$Active.energy', {$subtract:[{$size:'$Active'},1]} ]},
  10. {$arrayElemAt:['$Active.energy',0]} ] }
  11. }}
  12. ]);

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:

确定