Reputation: 457
Input is Once Document
{
"name": [
"abc",
"xyz"
],
"values": [
"123",
"100"
]
}
The explanation I want to Normalize the Array into multiple documents, abc
, and xyz
are dynamically coming, these are user define parameters
Expected Output
[
{
"data": {
"name": "abc",
"values": "123"
}
},
{
"data": {
"name": "xyz",
"values": "100"
}
}
];
Upvotes: 1
Views: 133
Reputation: 4452
Try this:
db.testCollection.aggregate([
{
$project: {
"data": {
$map: {
input: { $zip: { inputs: ["$name", "$values"] } },
as: "item",
in: {
name: { $arrayElemAt: ["$$item", 0] },
values: { $arrayElemAt: ["$$item", 1] }
}
}
}
}
},
{ $unwind: "$data" }
]);
Upvotes: 1
Reputation: 22296
What you want to do is use $zip, like so:
db.collection.aggregate([
{
$project: {
data: {
$map: {
input: {
$zip: {
inputs: [
"$name",
"$values"
]
}
},
as: "zipped",
in: {
name: {
"$arrayElemAt": [
"$$zipped",
0
]
},
values: {
"$arrayElemAt": [
"$$zipped",
1
]
}
}
}
}
}
},
{
$unwind: "$data"
},
{
$replaceRoot: {
newRoot: {
data: "$data"
}
}
}
])
Upvotes: 1