Reputation: 2174
I have documents with the following structure:
{
field1: 1
field2: 2
subdocument: {
subfield1: 3
subfield2: 4
subfield3: 5
...
}
}
I would like to $project
(or another operator if $project cannot do that?) so as to get:
The expected result would be:
{
field1: 1
field2: 2
subdocument: {
subfield1: 3
}
}
I first thought I would look for a way to apply a $project: {subfield1: 0}
only on the subdocument but could not find a solution.
Upvotes: 2
Views: 2515
Reputation: 13113
@SuleymanSah, 1 step with $mergeObjects
db.collection.aggregate([
{
$replaceRoot: {
newRoot: {
$mergeObjects: [
"$$ROOT",
{
"subdocument": {
subfield1: "$subdocument.subfield1"
}
}
]
}
}
}
])
Upvotes: 4
Reputation: 17888
Here is an ugly solution, but does the job.
db.collection.aggregate([
{
$addFields: {
"temp": "$subdocument.subfield1"
}
},
{
$project: {
"subdocument": 0
}
},
{
$addFields: {
"subdocument.subfield1": "$temp"
}
},
{
$project: {
"temp": 0
}
}
])
I am interested a simpler solution.
Upvotes: 1