For example, if I have a document like this
{
a: 1,
subdoc: {
b: 2,
c: 3
}
}
How can I convert it into a
Starting Mongo 4.2, the $replaceWith aggregation operator can be used to replace a document by another (in our case by a sub-document) as syntaxic sugar for the $replaceRoot mentioned by @chridam.
We can thus first include within the sub-document the root field to keep using the $set operator (also introduced in Mongo 4.2 as an alias for $addFields) and then replace the whole document by the sub-document using $replaceWith:
// { a: 1, subdoc: { b: 2, c: 3 } }
db.collection.aggregate([
{ $set: { "subdoc.a": "$a" } },
{ $replaceWith: "$subdoc" }
])
// { b: 2, c: 3, a: 1 }