When a text search query is performed on a model, a chained aggregate query will fail:
TestModel.text_search('qqq').sum(:some_field) # Mongo::Error::OperationFailure: $match with $text is only allowed as the first pipeline stage (17313)
This happens because the constructed pipeline contains the selector with query '$text': 'qqq' two times, which is prohibited by MongoDB:
Test.text_search('qqq').context.send(:pipeline, :some_field) # [{"$match"=>{:$text=>{:$search=>"qqq"}}}, # {"$match"=>{:$text=>{:$search=>"qqq"}, "some_field"=>{"$exists"=>true}}}, # {"$group"=> # ...
This duplication is made due to this commit fixing the issue MONGOID-4119:
https://github.com/mongodb/mongoid/commit/64085fffe15bf98d02de9d288a8d0e198799ce38
It seems, the previous commit on the same issue is perfectly working and lacks the specified flaw:
https://github.com/mongodb/mongoid/commit/8d8843b71e5adf56bea922c911bd1dc6b27286a6
Maybe, the line 128 in the broken commit was supposed to replace both 127 and 128, thus the line 127 is now redundant? Then no duplication will occur and the pipeline's matching stage seems to be ok.