From 8bc18f2367d616ef1e68b3be4acfaa1d2e8daa6e Mon Sep 17 00:00:00 2001 From: David Storch Date: Wed, 21 Jun 2017 15:07:52 -0400 Subject: SERVER-29647 Fix $match swapping to avoid moving before $sort-$limit. (cherry picked from commit 8b8845703f0c92bafca58ce5d9f36fd2327301d1) Conflicts: jstests/core/views/views_aggregation.js --- src/mongo/db/pipeline/document_source_sort.h | 4 +++- src/mongo/db/pipeline/pipeline_test.cpp | 23 +++++++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/mongo/db/pipeline/document_source_sort.h b/src/mongo/db/pipeline/document_source_sort.h index d9266011a55..0e4a427e77f 100644 --- a/src/mongo/db/pipeline/document_source_sort.h +++ b/src/mongo/db/pipeline/document_source_sort.h @@ -51,7 +51,9 @@ public: } bool canSwapWithMatch() const final { - return true; + // Can't swap with a $match if a limit has been absorbed, since in general match can't swap + // with limit. + return !limitSrc; } BSONObjSet getOutputSorts() final { diff --git a/src/mongo/db/pipeline/pipeline_test.cpp b/src/mongo/db/pipeline/pipeline_test.cpp index 0df5816a905..ed4ea7aefee 100644 --- a/src/mongo/db/pipeline/pipeline_test.cpp +++ b/src/mongo/db/pipeline/pipeline_test.cpp @@ -870,6 +870,27 @@ class MatchShouldNotSwapBeforeSkip : public Base { } }; +class MatchCannotSwapWithLimit : public Base { + string inputPipeJson() final { + return "[{$limit: 3}, {$match: {x: {$gt: 0}}}]"; + } + string outputPipeJson() final { + return inputPipeJson(); + } +}; + +class MatchCannotSwapWithSortLimit : public Base { + string inputPipeJson() final { + return "[{$sort: {x: -1}}, {$limit: 3}, {$match: {x: {$gt: 0}}}]"; + } + string outputPipeJson() final { + return "[{$sort: {sortKey: {x: -1}, limit: 3}}, {$match: {x: {$gt: 0}}}]"; + } + string serializedPipeJson() override { + return inputPipeJson(); + } +}; + } // namespace Local namespace Sharded { @@ -1492,6 +1513,8 @@ public: add(); add(); add(); + add(); + add(); add(); add(); add