Lucas Venezian Povoa
Lucas Venezian Povoa

Reputation: 569

How to merge several documents into a unique key value document?

I am trying to merge a set of documents into a collection A

{'s': 'v1', 'id': 1}
{'s': 'v2', 'id': 2}
{'s': 'v3', 'id': 3}
{'s': 'v4', 'id': 4}

into a unique document of key value pairs as fallow.

{
   'v1': 1,
   'v2': 2,
   'v3': 3,
   'v4': 4
}

Could you suggest a way to do that using a unique MongoDB command without persisting data in another collection?

Upvotes: 4

Views: 237

Answers (1)

NeNaD
NeNaD

Reputation: 20354

  • "$group" with $addToSet to create an array with key/value pairs from all documents
  • $set and $arrayToObject to make an object from the array generated in previous stage and assign it to the result field
  • $replaceRoot to replace the root with the result field generated in previous step
db.collection.aggregate([
  {
    "$group": {
      "_id": null,
      "result": {
        "$addToSet": {
          "k": "$s",
          "v": "$id"
        }
      }
    }
  },
  {
    "$set": {
      "result": {
        "$arrayToObject": "$result"
      }
    }
  },
  {
    "$replaceRoot": {
      "newRoot": "$result"
    }
  }
])

Working example

Upvotes: 4

Related Questions