Reputation: 3565
I have a document like this one:
{
'name': 'douglas'
'datetime_created': '2019-10-24',
'datetime_expiration': '2019-01-12'
}
I want to split this document into two documents, by the fields datetime_created
and datetime_expiration
.
Expected output:
{
'name': 'douglas'
'datetime_created': '2019-10-24'
},
{
'name': 'douglas'
'datetime_expiration': '2019-01-12'
}
How can I do this with aggregation
?
Upvotes: 5
Views: 1071
Reputation: 13113
In 3 steps:
Create array with 2 items + $unwind
+ $replaceRoot or $replaceWith
db.collection.aggregate([
{
$project: {
data: [
{
name: "$name",
datetime_created: "$datetime_created"
},
{
name: "$name",
datetime_expiration: "$datetime_expiration"
},
]
}
},
{
$unwind: "$data"
},
{
$replaceRoot: {
newRoot: "$data"
}
}
])
Upvotes: 5