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'
}
]
Query
$group
you can easily put them in an array, and i think its best to just do thisaggregate(
[{"$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}}])