(InvalidNamespace) {aggregate: 1} is not valid for '$addFields'; a collection is required

Latest Atlas update just broke a query that worked fine for a long time

This is a db.aggregate() pipeline that starts with a $documents stage and ends with a $merge stage using whenMatched sub-pipeline to reconcile new/existing versions of the document

This whenMatched sub-pipeline includes this $addFields stage that now throws this error. This seems like a wrong behavior because $addFields refers to the sub-pipeline that has proper collection namespace and not the high-level {aggregate: 1} pipeline

Could someone look into this and hopefully hotfix this error check ASAP?

hi @Dmitriy_Kruglyak
Could you please provide the full pipeline, on which version it worked, and on which one it is not working?
Thank you

Here is the exact test case/ error in mongosh:

> db.version()
<7.2.0
>db.aggregate([
{"$documents": {"$literal": [{a: 1}]}},
{"$merge": {"into": "test", "on": ["_id"], "whenMatched": [
	{ "$addFields"    : {"_merged"              : "$$new"}}
]}}
 ])
<MongoServerError: {aggregate: 1} is not valid for '$addFields'; a collection is required.

It was working just fine earlier last week, not clear what version it was

1 Like

Hi @Dmitriy_Kruglyak,
The syntax is:
db.collection_name.aggregate(…)

Here is explained the error:

Regards

thank you. you can track this ticket https://jira.mongodb.org/browse/SERVER-85892

1 Like

Wrong, aggregation without collection is supported: https://www.mongodb.com/docs/manual/reference/method/db.aggregate/

We have to rely on this for inserting/merging documents, like what our query does

1 Like

Thanks for filing this JIRA as critical. Any idea if/when we could have a hotfix? What is the typical release timeframe (with push to Atlas) for bugs like this?

After the fix is implemented, it may take a few weeks to get to Atlas, hard to say now.
If you can’t wait, I’d suggest using a workaround, e.g., substituting $documents with something like:

db.test.aggregate([
  {$limit: 1},
  { $project: {docs: [<array of documents>]} }, 
  {$unwind: '$docs'},
  {$replaceRoot: { newRoot: '$docs'  }},
  { $merge: { ... }}
])