1

I have MongoDB documents in the following format which represent a location:

{
  "_id": "632987336a2913f401318f82",
  "name": "1 Ave, Infinite Loop St",
  "timezone": "Europe/Paris",
  "location": {
    "lat": 48.858093,
    "lng": 2.294694
  },
  "detections": [
    {
      "approach": "North Bound",
      "class": "Person",
      "datetime": "05:00 pm",
      "lane": 3,
      "movement": "Through"
    },
    {
      "approach": "North Bound",
      "class": "Person",
      "datetime": "05:00 pm",
      "lane": 3,
      "movement": "Through"
    },
   // ...more detections
  ]
}

I know the _id of the site that I want to fetch but what I want to do is that when I fetch this site, I only need the detections from the last 7 days using the datetime property in the detections object. However, I am unsure of how to achieve this using mongoose. Currently, I am trying to achieve this manually by just fetching all the site detections and then filtering them by myself but this is a tedious approach. Currently, this is how I am fetching the site detections:

const site = await SiteModel.findById(siteID);
const detections = site.detections;

This answer tells of a way to implement this behavior but this is using aggregate and in my case the key is nested in an array of objects. I am new to MongoDB so any help is appreciated.+

chomprrr
  • 406
  • 4
  • 15

1 Answers1

0
  1. you need to store timestamps in "datetime" fields.
  2. you can use this $elemMatch to filter specific data from the array of objects.