Database
[{"_id":ObjectId("5e39d6a0330c130006a042c6"),"collectorItemId":ObjectId("5e33a6b9887ef5000620a0c0"),"firstEverCommit":false,"scmUrl":"sampleRepo1","scmBranch":"master","scmRevisionNumber":"a2ad6842468eb55bffcbe7d700b6addd3eb11629","scmAuthor":"son123","scmCommitTimestamp":NumberLong(1580841662000)},{"collectorItemId":ObjectId("5e33a6b9887ef5000620a0c0"),"firstEverCommit":false,"scmUrl":"sampleRepo1","scmBranch":"develop","scmRevisionNumber":"b2ad6842468eb55bffcbe7d700b6addd3eb11629","scmAuthor":"son123","scmCommitTimestamp":NumberLong(1581958504000)}]
Query
db.collection.aggregate([{"$match":{"scmBranch":"master"}},{"$group":{"_id":"$scmUrl","recentcommitdate":{"$max":"$scmCommitTimestamp"}}},{"$lookup":{"from":"collection","let":{"scmUrl":"$_id","recentcommitdate":"$recentcommitdate"},"pipeline":[{"$match":{"$expr":{"$and":[{"$eq":["$scmBranch","develop"]},{"$eq":["$scmUrl","$$scmUrl"]},{"$gte":["$scmCommitTimestamp","$$recentcommitdate"]}]}}},{"$sort":{"scmCommitTimestamp":-1}}],"as":"commits"}},{"$match":{"commits.0":{"$exists":true}}},{"$project":{"commits":{"$size":"$commits"},"lastcommit":{"$arrayElemAt":["$commits",0]},"firstcommit":{"$arrayElemAt":["$commits",-1]}}}])