Home > Mobile >  Convert embedded documents into separate documents in mongodb
Convert embedded documents into separate documents in mongodb

Time:12-29

I have the below documents.

[
  {
    "content": {
      "abc123": {
        "_id": "abc123",
        "total": 189,
        "published": 189,
        "created": 0,
        "approved": 0,
        "rejected": 0,
        "sent_for_approval": 0
      },
      "abc124": {
        "_id": "abc124",
        "total": 1911,
        "published": 1899,
        "created": 10,
        "approved": 2,
        "rejected": 0,
        "sent_for_approval": 0
      }
    }
  },
  {
    "content": {
      "abc124": {
        "_id": "abc124",
        "total": 1911,
        "published": 1899,
        "created": 10,
        "approved": 2,
        "rejected": 0,
        "sent_for_approval": 0
      }
    }
  }
]

how to convert this objects of key value pair into separate documents like below without duplicatesenter code here:

[
  {
    "_id": "abc123",
    "total": 189,
    "published": 189,
    "created": 0,
    "approved": 0,
    "rejected": 0,
    "sent_for_approval": 0
  },
  {
    "_id": "abc124",
    "total": 1911,
    "published": 1899,
    "created": 10,
    "approved": 2,
    "rejected": 0,
    "sent_for_approval": 0
  }
]

CodePudding user response:

Query

  • convert obect to array
  • unwind and replace root (so each embedded document to be a separated root document)
  • group by key and keep only the first to remove the duplicates
  • replace root to get the expected output

Test code

aggregate(
[{"$set":{"content":{"$objectToArray":"$content"}}},
 {"$unwind":"$content"},
 {"$replaceRoot":{"newRoot":"$content"}},
 {"$group":{"_id":"$k", "doc":{"$first":"$v"}}},
 {"$replaceRoot":{"newRoot":"$doc"}}])
  • Related