I want to get all documents that (grouped by 2 fields) are not equal to their max.
There are multiple versions for every document, so the query to view all the latest versions is:
db.getCollection('datatype').aggregate(
[
{
$group:
{
_id: {
"name": "$name",
"applicationId": "$applicationId"
},
latest: { $max: "$version" }
}
}
]
)
Now I need the complement of this query (all previous versions, not the latest).
I tried some queries, like the below, but none worked.
db.getCollection('datatype').aggregate(
[
{
$group:
{
_id: {
"name": "$name",
"applicationId": "$applicationId"
},
previousVersions:
{ $ne: {$max: "$version"} }
}
}
]
)
EDIT: input/output examples: input:
db.getCollection('datatype').insertMany([
{ applicationId: "AAAA", name: "foo", version: NumberInt(1) },
{ applicationId: "AAAA", name: "foo", version: NumberInt(2) },
{ applicationId: "AAAA", name: "foo", version: NumberInt(3) },
{ applicationId: "BBBB", name: "foo", version: NumberInt(1) },
{ applicationId: "CCCC", name: "bar", version: NumberInt(1) },
{ applicationId: "CCCC", name: "bar", version: NumberInt(2) }
])
So the expected results from the first query that takes the latest version from applicationId+name, is:
{ applicationId: "AAAA", name: "foo", version: NumberInt(3) },
{ applicationId: "BBBB", name: "foo", version: NumberInt(1) },
{ applicationId: "CCCC", name: "bar", version: NumberInt(2) }
And my desired output is basically the complement of this query, that takes all the results besides the latest version (all these documents has an updated version, for their corresponding applicationId+name)
{ applicationId: "AAAA", name: "foo", version: NumberInt(1) },
{ applicationId: "AAAA", name: "foo", version: NumberInt(2) },
{ applicationId: "CCCC", name: "bar", version: NumberInt(1) }