document 1:
{
_id: abcdef,
name: "foo",
time: [1234],
doc: [1234]
}
document 2:
{
_id: alexa,
name: "alexa",
time: [1234],
doc: [1234]
}
Expected output:
{
time[1234],
alexa[1234],
foo[1234]
}
I have multiple documents in MongoDB, I want to merge the document and make it one document.
Playground merge multiple documents into one.
You can try,
$addFields convert name and doc as object using $arrayToObject in root field$group by mull and merge objects in root using $mergeObjects$addFields time to get union time from array of array using $reduce and $setUnion$replaceRoot to replace merged object from root field and time field using $mergeObjectsdb.collection.aggregate([
{
$addFields: {
root: {
$arrayToObject: [[{ k: "$name", v: "$doc" }]]
}
}
},
{
$group: {
_id: null,
root: { $mergeObjects: "$root" },
time: { $push: "$time" }
}
},
{
$addFields: {
time: {
$reduce: {
input: "$time",
initialValue: [],
in: { $setUnion: ["$$this", "$$value"] }
}
}
}
},
{
$replaceRoot: {
newRoot: {
$mergeObjects: ["$root", { time: "$time" }]
}
}
}
])
Playground
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With