Merging two documents from same collection - mongoose

Viewed 31

I have multiple documents in a collection with data field as array of string. I want to perform following operations:-

  1. Compare data field of one selected document with other documents data field.
  2. If any one of the value from selected data field matches with other document data field, I want to merge the documents together

Input:

{
  "_id": "6323ec74eee734b4ba790f4c",
  "data": [
    "test 1", "test 2", "test 3"
  ],
  "__v": 0
}

{
  "_id": "6323ec74eee78fb4ba790fd3",
  "data": [
    "test 1", "test 8", "test 100"
  ],
  "__v": 0
}

{
  "_id": "6323ec74eee78fb4ba790f98",
  "data": [
    "test 83", "test 2", "test 123"
  ],
  "__v": 0
}

Newly merged document will be like

Output:

{
  "_id": "6323ec74eee78fb4ba790f98",
  "data": [
    "test 1", "test 2", "test 3", "test 8", "test 100", "test 83", "test 123"
  ],
  "__v": 0
}

1 Answers

When you want to group all the documents, you need to add {_id: null}

It means group all documents.

So you can try this:

  db.collection.aggregate([
  {
    "$unwind": "$data"
  },
  {
    $group: {
      _id: null,
      data: {
        "$addToSet": "$data"
      }
    }
  }
])

output:

[
  {
    "_id": null,
    "data": [
      "test 2",
      "test 8",
      "test 100",
      "test 83",
      "test 123",
      "test 3",
      "test 1"
    ]
  }
]
Related