Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert multiple documents into one documents in MongoDB

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.

like image 554
bc110402922 Avatar asked Nov 23 '25 22:11

bc110402922


1 Answers

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 $mergeObjects
db.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

like image 149
turivishal Avatar answered Nov 25 '25 17:11

turivishal