SERVER-114196 Fix $unionWith system variables initialization (#44444)

GitOrigin-RevId: cacd16d51c46e07a2b1b427c155847a7856c0267
This commit is contained in:
Ivan Fefer 2025-12-02 18:03:29 +01:00 committed by MongoDB Bot
parent d8cc9dd86b
commit 382b41c9d6
2 changed files with 33 additions and 0 deletions

View File

@ -0,0 +1,31 @@
/**
* Test that $unionWith works when system variables are used after it and pushed in $unionWith
* during optimization.
* @tags: [
* do_not_wrap_aggregations_in_facets,
* assumes_unsharded_collection,
* ]
*/
const testDB = db.getSiblingDB(jsTestName());
const coll = testDB.coll;
coll.drop();
assert.commandWorked(coll.insertOne({a: 1}));
const date = new Date();
const data =
coll.aggregate([{$unionWith: {coll: coll.getName(), pipeline: []}}, {$project: {now: "$$NOW"}}])
.toArray();
assert.eq(data.length, 2);
for (let doc of data) {
const diff = Math.abs(doc.now.getTime() - date.getTime());
assert.lte(
diff, 60000, "Expected $$NOW to be close to current time. Difference was " + diff + "ms");
}
assert.doesNotThrow(() => {
coll.explain("executionStats").aggregate([
{$unionWith: {coll: coll.getName(), pipeline: []}},
{$project: {now: "$$NOW"}},
]);
});

View File

@ -324,6 +324,7 @@ DocumentSource::GetNextResult DocumentSourceUnionWith::doGetNext() {
// context of the unionWith '_pipeline' as part of DocumentSourceUnionWith constructor.
// Attach query settings to the '_pipeline->getContext()' by copying them from the
// parent query ExpressionContext.
_pipeline->getContext()->initializeReferencedSystemVariables();
_pipeline->getContext()->setQuerySettingsIfNotPresent(pExpCtx->getQuerySettings());
LOGV2_DEBUG(9497002,
@ -508,6 +509,7 @@ Value DocumentSourceUnionWith::serialize(const SerializationOptions& opts) const
// NOTE: this is done here, as opposed to at the beginning of the serialize() method
// because serialize() is called when generating query shape, however, at that
// moment no query settings are present in the parent context.
_pipeline->getContext()->initializeReferencedSystemVariables();
_pipeline->getContext()->setQuerySettingsIfNotPresent(pExpCtx->getQuerySettings());
return pExpCtx->getMongoProcessInterface()->preparePipelineAndExplain(ownedPipeline,