1

I have a use-case where I need to fetch max value from one interval and min value from another interval. This has to happen for all unique domains in collection. This collection contains domain and when it was visited. Domain can be visited several time so collection will have multiple rows for each visit.

Since these two intervals are adjacent I can fetch all records in one query but I have to calculate min/max values at application side. Another way is to have two separate queries for min from one interval and max from another interval. Just curious if it can be optimised in a way that single query performs this job. Below are my two aggregation queries:

Aggregation 1:

List(
  MongoDBObject(
    "$match" -> MongoDBObject("stamp" -> MongoDBObject("$gte" -> T1, "$lt" -> T2))
  ),
  MongoDBObject(
    "$group" -> MongoDBObject(
      "_id" -> "$key",
      "stamp" -> MongoDBObject("$max" -> "$stamp")
    )
  )
)

Aggregation 2:

List(
  MongoDBObject(
    "$match" -> MongoDBObject("stamp" -> MongoDBObject("$gte" -> T2, "$lt" -> T3))
  ),
  MongoDBObject(
    "$group" -> MongoDBObject(
      "_id" -> "$key",
      "stamp" -> MongoDBObject("$min" -> "$stamp")
    )
  )
)

Here T1 < T2 < T3 and stamp is a timestamp i.e. long value. Below is sample document from collection:

{
  "_id" : ObjectId("6048b0b7fe4b987f2e251705"),
  "key" : "JW9oIzDYlV.com",
  "stamp" : NumberLong("1612784569678"),
}
Shailesh
  • 358
  • 2
  • 13

0 Answers0