I want a query that will take the latest version out of each document, and check if some given string (applicationId
) is in the list allowedApplications
.
documents example:
{
"applicationId" : "y...",
"allowedApplications": ["x..."],
"name" : "some-name",
"version" : 3
}
{
"applicationId" : "y...",
"allowedApplications": ["x..."],
"name" : "some-name",
"version" : 2
}
{
"applicationId" : "x...",
"allowedApplications": ["y..."],
"name" : "some-other-name",
"version" : 1
}
So the MongoDB query is:
db.getCollection('..').aggregate(
[
{ "$match": { "allowedApplications": "x..." }},
{"$group": { "_id": "$name", "version": { "$max": "$version" }}}
]
)
And the query will output the name and version (I'll perhaps add the allowedApplications
later).
I'm trying now to write this in Scala's mongodb driver.
I tried a bunch of stuff, for example:
collection
.aggregate(List(
`match`(equal("allowedApplications", "x..")),
group("$name", addToSet("version", addToSet("$max", "¢version")))
)
)
But couldn't get it to work.
Using Scala 2.13.1 and mongo-scala-driver 4.1.0. Any help would be appreciated.
Found the answer:
collection
.aggregate(List(
`match`(equal("allowedApplications", "x...")),
group("$name", max("version", "$version"))
)
The order isn't quite the same, but just use the function in the accumulator field.