0

Am new to MongoDB and I have two arrays in a document like this. I want to get a specific value from both arrays. For example "received_bytes" and its value from the values array "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.

2
  • if you can give valid JSON data and the expected output Commented Nov 23, 2021 at 18:55
  • @Takis_ Its already real json data. Commented Nov 24, 2021 at 11:58

1 Answer 1

1

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' },
    },
  },
]);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.