Search code examples
javascriptnode.jsmongodbmongoosemongodb-query

Move embedded documents in mongoDB into new documents


{
  "_id": {
    "$oid": "2534c6893d643531411"
  },
  "id": "854",
  "920543": {
    "createdAt": 1667210991769,
  },
  "750544": {
    "createdAt": 1693292609,
  },
  "719572": {
    "createdAt": 1693292739,
}

I am trying to go through every document in a collection and move all the embedded documents within the document and create a new document for each embedded document with the key such 750544, 719572 as the messageId field in the new id, and the rest of the data such as createdAt as a normal field. I also want to keep the id field the same in the new documents.

Example documents based on the above would look like

{
  "_id": {
    "$oid": "someIdGeneratedbyMongo"
  },
  "id": "854",
  "messageId": "920543",
  "createdAt": 1667210991769
},
{
  "_id": {
    "$oid": "someIdGeneratedbyMongo"
  },
  "id": "854",
  "messageId": "750544",
  "createdAt": 1693292609
},
{
  "_id": {
    "$oid": "someIdGeneratedbyMongo"
  },
  "id": "854",
  "messageId": "719572",
  "createdAt": 1693292739
}

etc


Solution

    1. $set - Create a data array field with the value of converting all the fields in the current document (excluding the _id and id fields) to the document with k and v fields.

    2. $unwind - Deconstruct the data array field.

    3. $project - Decorate the output documents.

    db.collection.aggregate([
      {
        $set: {
          data: {
            $filter: {
              input: {
                $objectToArray: "$$ROOT"
              },
              cond: {
                $not: {
                  $in: [
                    "$$this.k",
                    [
                      "_id",
                      "id"
                    ]
                  ]
                }
              }
            }
          }
        }
      },
      {
        $unwind: "$data"
      },
      {
        $project: {
          id: 1,
          messageId: "$data.k",
          createdAt: "$data.v.createdAt"
        }
      }
    ])
    

    Demo @ Mongo Playground