Skip to content

Instantly share code, notes, and snippets.

@xymor
Created April 19, 2018 21:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xymor/a1c297383673a1e5bace99395f5043d3 to your computer and use it in GitHub Desktop.
Save xymor/a1c297383673a1e5bace99395f5043d3 to your computer and use it in GitHub Desktop.
How to run a mongo aggregation pipeline using plain json mongo query insteal of spring data dsl
fun reportServices(stores: List<Store>, start: LocalDate, end: LocalDate, pageable: Pageable): Pair<List<java.util.HashMap<*, *>>, Int> {
val pipeline = """
[
{#match: {
'processed.accountingCodePrimary': {#ne: null},
'processed.specialization': {#ne: 'NONE'},
'processed.authorizer.#id': {#eq: 'WK'},
'processed.transactionCodeConsult': {#ne: 'YES'}
}},
{#group: {_id: {'store': '#processed.store', 'date': '#processed.transactionDate', 'eType': '#processed.transationStatus'}, 'eAmount': {#sum: '#processed.mongoAmount'}}},
{#group: {_id: {'store': '#_id.store', 'date': '#_id.date'},
'eTotais': {#push: {'type': '#_id.eType', 'total': '#eAmount'}}}},
{#lookup: {from: 'workingDay', localField: '_id.store', foreignField: 'store', as: 'wstore'}},
{#unwind: '#wstore'},
{#unwind: '#wstore.departments'},
{#addFields: {'wstore.date1': {#dateToString: {format: "%Y%m%d", date: "#wstore.day"}}}},
{#addFields: {'wstore.date2': {#substr: [ '#_id.date', 0, 8 ]}}},
{#addFields: {'wstore.equalDates': {#strcasecmp: ['#wstore.date1', '#wstore.date2']}}},
{#match: {'wstore.departments.number': "998", 'wstore.equalDates': 0 }},
{#project: {'_id': '#_id', 'eTotais': '#eTotais', 'eTotais': '#eTotais', 'totais': [{"type" : "VENDA","total" : '#wstore.departments.total'}] }},
{'#sort': {'_id.date': -1}}
]
""".queryalize()
val storeDateFilter = """
[{'#match': {'#and': [
{'processed.transactionDate': {#gte: ${start.format(DateTimeFormatter.BASIC_ISO_DATE)}}},
{'processed.transactionDate': {#lte: ${end.format(DateTimeFormatter.BASIC_ISO_DATE)}}},
{'processed.store.#id': {'#in': [${stores.joinToString { it.id.toString() }}]}}
]}
}]
""".queryalize()
val countStage = """
[{ #count: "registeredTotal" }]
""".queryalize()
val pageStage = """
[{ #skip: ${pageable.offset} },
{ #limit: ${pageable.pageSize} }]
""".queryalize()
val aggregationCount = BasicDBObject("aggregate", "electronicOperation")
.append("pipeline", storeDateFilter + pipeline + countStage)
val aggregation = BasicDBObject("aggregate", "electronicOperation")
.append("pipeline", storeDateFilter + pipeline + pageStage)
val basic = (mongoTemplate.executeCommand(aggregationCount).get("result") as BasicDBList)
val count = if(basic.size > 0) (basic.get(0) as BasicDBObject)["registeredTotal"] as Int else 0
val out = mongoTemplate.executeCommand(aggregation).get("result")
val result = if(out!=null) out as List<java.util.HashMap<String,Any>> else listOf()
return Pair(result, count)
}
fun String.queryalize(): BasicDBList {
return this.trimMargin().replace("#","$")
.let{ com.mongodb.util.JSON.parse(it) } as BasicDBList
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment