简体   繁体   English

MongoDB:文档中两个 arrays 的合计值(映射)

[英]MongoDB : aggregate value from two arrays in document (mapping)

Am new to MongoDB and I have two arrays in a document like this.我是 MongoDB 的新手,我在这样的文档中有两个 arrays。 I want to get a specific value from both arrays.我想从 arrays 中获取特定值。 For example "received_bytes" and its value from the values array "43118304".例如“received_bytes”及其值数组“43118304”中的值。 I did some research but I think am lost.我做了一些研究,但我认为迷路了。

fields:{
 "time",
 "received_bytes",
 "sent_bytes"
}
values:{
 "2021-11-22T08:08:30Z",
 43118304,
 43105744
}

Basic aggregate I have done我已经完成的基本聚合

return await Metric.aggregate([
  {
    $match: matches,
  },
  { $sort: { _id: 1 } },
  {
    $group: {
      _id: params.field, // received_bytes
      values: { $push: '$values' }, // array of values for received_bytes
    },
  },
]);

What i expect:我的期望:

{
  _id:"received_bytes",
  values:[] //all received_bytes values
}

Thanks for help.感谢帮助。

I didn't find best answer so I grouped the results then loop on them to get my values我没有找到最佳答案,所以我将结果分组然后循环它们以获得我的值

 const metrics = await Metric.aggregate([
  {
    $match: matches,
  },
  { $sort: { _id: 1 } },
  // mapping fields=>values where field equal to params.field
  {
    $group: {
      _id: '$fields',
      values: { $push: '$values' },
    },
  },
]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM