-
Type:
Bug
-
Resolution: Fixed
-
Priority:
Critical - P2
-
Affects Version/s: 8.0.13
-
Component/s: None
-
Query Optimization
-
Fully Compatible
-
ALL
-
v8.2, v8.0
-
None
-
None
-
None
-
None
-
None
-
None
-
None
I have a collection with elements of the following structure:
{ device: "M57906", date: some date }
and one index { device: 1, date: 1 }
The query with $bottom does not return the correct result.
This only happens when the index exists.
h4s> db.events.aggregate([{ $sort: { device: 1, date: 1 } }, { $group: { _id: "$device", obj: { $bottom: { output: "$date", sortBy: { date: -1 } } } } }])
[ \{ _id: 'M57906', obj: ISODate('2025-08-28T09:46:33.017Z') } ]
h4s> db.events.aggregate([{ $sort: { device: 1, date: 1 } }, { $group: { _id: "$device", obj: { $bottomN: { n: 1, output: "$date", sortBy: { date: -1 } } } } }])
[ \{ _id: 'M57906', obj: [ ISODate('2025-07-06T00:00:01.305Z') ] } ]
winning plan for $bottom query:
isCached: false, stage: 'PROJECTION_COVERED', transformBy: \{ date: 1, device: 1, _id: 0 }, inputStage: { stage: 'DISTINCT_SCAN', keyPattern: \{ device: 1, date: 1 }, indexName: 'device_1_date_1', isMultiKey: false, multiKeyPaths: \{ device: [], date: [] }, isUnique: false, isSparse: false, isPartial: false, indexVersion: 2, direction: 'backward', indexBounds: { device: [ '[MaxKey, MinKey]' ], date: [ '[MaxKey, MinKey]' ] } }
winning plan for $bottomN: n: 1 query
{
isCached: false,
queryPlan: {
stage: 'GROUP',
planNodeId: 3,
inputStage: {
stage: 'PROJECTION_COVERED',
planNodeId: 2,
transformBy: \{ date: true, device: true, _id: false },
inputStage: {
stage: 'IXSCAN',
planNodeId: 1,
keyPattern: \{ device: 1, date: 1 },
indexName: 'device_1_date_1',
isMultiKey: false,
multiKeyPaths: \{ device: [], date: [] },
isUnique: false,
isSparse: false,
isPartial: false,
indexVersion: 2,
direction: 'forward',
indexBounds: {
device: [ '[MinKey, MaxKey]' ],
date: [ '[MinKey, MaxKey]' ]
}
}
}
},
slotBasedPlan: {
slots: '$$RESULT=s9 env: \{ s4 = SortSpec({"date" : -1}) }',
stages: '[3] project [s9 = newBsonObj("_id", s6, "obj", s8)] \n' +
'[3] project [s8 = aggBottomNFinalize(s7, s4)] \n' +
'[3] group [s6] [s7 = aggBottomN(s4, null, getSortKeyDesc(s2), (s2 ?: null)) init\{[[], 0ll, 1ll, 0, 104857600, true]}] spillSlots[s5] mergingExprs[aggBottomNMerge(s5, s4)] \n' +
'[3] project [s6 = (s1 ?: null)] \n' +
'[1] ixseek KS(0A0A0104) KS(F0F0FE04) none s3 none none lowPriority [s1 = 0, s2 = 1] @"edc48567-cea3-4782-97fe-7173105114f2" @"device_1_date_1" true '
}
}
$top is also broken in the same way.
- is caused by
-
SERVER-84347 Use DISTINCT_SCAN with $top/$bottom accumulators
-
- Closed
-
- is related to
-
SERVER-90017 Parse firstN/lastN/minN/maxN/topN/bottomN with n = 1 into a corresponding first/last/min/max/top/bottom
-
- Closed
-
- related to
-
SERVER-85213 Rewrite $sort+$group with $first/$last to use $top/$bottom
-
- Backlog
-
-
SERVER-113145 Use distinct scan for $group+$top/$bottom and $sort when sort orders are compatible
-
- Open
-