Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to merge multiple documents in MongoDB and convert fields' values into fields

I have a MongoDB collection that I have managed to process using an aggregation pipeline to produce the following result:

[ 
  { 
    _id: 'Complex Numbers', 
    count: 2 
  }, 
  { _id: 'Calculus', 
    count: 1 
  }
]

But the result that I am aiming for is something like the following:

{
  'Complex Numbers': 2,
  'Calculus': 1
}

is there a way to achieve that?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Query

  • to convert to {} we need somethings like [[k1 v1] ...] OR [{"k" "..." :v "..."}]
  • first stage
    • converts each document to [{"k" ".." , "v" ".."}]
    • then arrayToObject
    • and replace root
  • so we have each document like "Complex Numbers": 2
  • the group is used to combine all those documents in 1 document
  • and then replace the root with that one document

Test code here

aggregate(
[{"$replaceRoot": 
    {"newRoot": {"$arrayToObject": [[{"k": "$_id", "v": "$count"}]]}}},
  {"$group": {"_id": null, "data": {"$mergeObjects": "$$ROOT"}}},
  {"$replaceRoot": {"newRoot": "$data"}}])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading