1

With my data structure like shown below I want to do some aggregation on specific datasets. I need all datasets with first target score of 3.

But I also need to get only datasets in a specific time interval. In my case I need all datasets with admission time between 8 am and 4 pm. How do I do that?

structure

{
    "_id" : ObjectId("5d7f6a937563a63c1d8b4639"),
    "admission" : ISODate("2019-09-16T10:27:20.197Z"),
    "target" : [
        {
            "score" : 3
        },
    {
            "score" : 2
        }
    ]
}

get datasets with score of 3

db.data.aggregate([
{
    $match : {"target.0.score": 3}
},
{
  // ...
}
])
user3142695
  • 15,844
  • 47
  • 176
  • 332
  • you can use **`$gte`** and **`$lte`** operator on **admission** field – niranjan_harpale Oct 24 '19 at 11:11
  • @niranjanharpale I don't think so, as I want to get all datasets on all different dates, but only in a specific **time** range – user3142695 Oct 24 '19 at 11:15
  • 1
    Sooo. By no means the first to ask this. Again the only *sane* approach is where things like the *time of day* matters to you regardless of the dates it falls within, then the logical course is to actually store that *time* as a **separate** value. It's *"possible"* of course with aggregation operations, **but** it's really *horrible* for performance, since a calculation is essentially performed against every eligible item. As in *"a lot more"* than you actually want in your results. Store the time separately. – Neil Lunn Oct 24 '19 at 11:19
  • 1
    So, closed as duplicate since the only answers this is likely to attract are basically the *"silly aggregation approach"* ( which you should not do ), or basically take the advise of storing the time separately. Which you probably won't *want to do*, but it's really the only sane option that scales. – Neil Lunn Oct 24 '19 at 11:22
  • @NeilLunn Ok, understand that. But then I have to transform my existing data. I have to get the time of each dataset and update it with the time. Is it possible to do this directly in mongodb console or do I have to do that in a script? – user3142695 Oct 24 '19 at 11:22
  • 1
    See [Update MongoDB field using value of another field](https://stackoverflow.com/questions/3974985/update-mongodb-field-using-value-of-another-field). It depends on your MongoDB version. With MongoDB 4.2 and upwards, it's possible in a single update statement. – Neil Lunn Oct 24 '19 at 11:25

0 Answers0