0

I have the following document structure:

{
  "_id": "5d2708ff79263ba40e54c08c",
  "meta": {
    "uid": "dd41ca10-a3c2-11e9-a1dd-fbec9d04cb25",
    "firmware": "0.0.1",
    "timestamp": "2019-07-11T10:01:35.264Z"
  },
  "sensors": [
    {
      "_id": "5d2708ff79263ba40e54c08e",
      "name": "sensor1",
      "value": 0.09050827850822706
    },
    {
      "_id": "5d2708ff79263ba40e54c08d",
      "name": "sensor2",
      "value": 0.06592630654288716
    }
  ]
}

What I'm trying to do is to select all documents per minute and then calculate every sensor's average value and get something like this:

{
  "_id": "5d2708ff79263ba40e54c08c",
  "meta": {
    "uid": "dd41ca10-a3c2-11e9-a1dd-fbec9d04cb25",
    "firmware": "0.0.1",
    "timestamp": "2019-07-11T10:01:35.264Z"
  },
  "sensors": [
    {
      "_id": "5d2708ff79263ba40e54c08e",
      "name": "sensor1",
      "avg": 0.1111111
    },
    {
      "_id": "5d2708ff79263ba40e54c08d",
      "name": "sensor2",
      "avg": 0.2222222
    }
  ]
}

It is a little bit confusing after years of working with relational databases.

Nikita Zernov
  • 5,465
  • 6
  • 39
  • 70
  • 1
    This [answer](https://stackoverflow.com/a/26814496) should give you some leeway in how you can aggregate documents per time interval and you can use [`$unwind`](https://docs.mongodb.com/manual/reference/operator/aggregation/unwind/) to flatten the `sensors` array then aggregate to find the average – chridam Jul 11 '19 at 10:57
  • Selecting documents in a time period is not a problem, I am doing it with match in earlier stage. Problem is to find average in nested array. – Nikita Zernov Jul 11 '19 at 11:20
  • 1
    Is it possible for you to update your question providing a sample of documents and what your expected output is from that batch of example documents? – chridam Jul 11 '19 at 11:59
  • There are two documents in question. Every device generates first document every second. Now there is bunch of this documents and I want to get average value of every sensor (like document 2). – Nikita Zernov Jul 11 '19 at 12:28
  • Duplicate of https://stackoverflow.com/questions/26814427/group-result-by-15-minutes-time-interval-in-mongodb/26814496#26814496 – Ashh Jul 12 '19 at 07:46

0 Answers0