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

Time:12-03

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?

CodePudding user response:

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"}}])
  • Related