Reputation: 1542
I have one collection say user
. Structure of each document is something like this
_id:String
status:Int32
account:{
firstName:
lastName:
.. some other nested property
}
..some more property
My end goal is to generate a new nested field fullName
in account
field which is a concatenation of two name fields. I can run aggregate
query like this
db.user.aggregate(
[
{ $project: { 'account.name': { $concat: [ "$account.firstName", " ", "$account.lastName" ] } } }
])
if I write $out
along with db name, but my existing data get replaced. How do I actually merge so that my final structure remains as
_id:String
status:Int32
account:{
firstName:String
lastName:String
fullName:String
.. some other nested property
}
..some more property
Upvotes: 1
Views: 560
Reputation: 103305
In your $project
pipeline, you need to include the other fields using the dot notation on the embedded fields as follows:
db.user.aggregate([
{
"$project": {
"status": 1,
"field1": 1, // the other properties
"field2": 1,
"account.firstName": 1,
"account.lastName": 1,
"account.name": {"$concat":["$account.firstName", " ", "$account.lastName"]}
}
},
{ "$out": "tempcollection" }
])
Upvotes: 1