Home > Mobile >  Mongo Query - $group
Mongo Query - $group

Time:02-04

Is it possible with Mongo to make this transformation (with a $group I think) ? or should it be done with JavaScript on the client side ?

[
  {
    id: 1,
    lib: 'x'
  },
  {
    id: 2,
    lib: 'a'
  },
  {
    id: 1,
    lib: 'b'
  },
  {
    id: 1,
    lib: 'v'
  }
]

to

[
  {
    id: 1,
    lib_1: 'x',
    lib_2: 'b',
    lib_3: 'v'
  },
  {
    id: 2,
    lib_1: 'a'
  }
]

CodePudding user response:

Query

  • with $group you can easily put them in an array, and i think its best to just do this
  • but if you want the exact output like in your expected output its more complicated, because you need to convert array to object, and add numbers in keys etc, in general in mongodb fields are not made for data, because queries become harder, fields are for the schema

Playmongo

aggregate(
[{"$group": {"_id": "$id", "libs": {"$push": "$lib"}}},
 {"$set": 
   {"libs": 
     {"$map": 
       {"input": {"$range": [0, {"$size": "$libs"}]},
        "in": 
         {"k": {"$concat": ["lib_", {"$toString": {"$add": ["$$this", 1]}}]},
          "v": {"$arrayElemAt": ["$libs", "$$this"]}}}}}},
 {"$set": {"libs": {"$arrayToObject": ["$libs"]}}},
 {"$replaceRoot": {"newRoot": {"$mergeObjects": ["$libs", "$$ROOT"]}}},
 {"$project": {"libs": 0}}])
  • Related