change key document mongodb aggregate
To create a nested object with dynamic key you need to use $arrayToObject which takes an array of keys (k
) and values
(v
) as a parameter. Then you can use $replaceRoot to promote that new object to a root level. You need MongoDB 4.0 to convert ObjectId
to string
using $toString operator
db.col.aggregate([ { $replaceRoot: { newRoot: { $arrayToObject: { $let: { vars: { data: [ { k: { $toString: "$_id" }, v: "$serie" } ] }, in: "$$data" } } } } }])
Outputs:
{ "5b97f6cea37f8c96db70fea9" : { "_id" : ObjectId("5a55f988b6c9dd15b47faa2a"), "updatedAt" : ISODate("2018-02-09T13:22:54.521Z"), "createdAt" : ISODate("2018-01-10T11:31:20.978Z"), "deletar" : false, "infantil" : false, "status" : true, "turma" : [ ] }}
If you want to get rid of _id
in your result you can specify fields explicitly in v
like:
v: { updatedAt: "$serie.updatedAt", createdAt: "$serie.createdAt", ... }
You can use below aggregation pipeline in 4.0.
db.colname.aggregate([ {"$addFields":{"idstr":{"$toString":"$_id"}}}, {"$project":{"serie._id":0}}, {"$replaceRoot":{"newRoot":{"$arrayToObject":[[["$idstr","$serie"]]]}}}])
You can use one more trick using $group
aggregation stage.
db.collection.aggregate([ { "$group": { "_id": null, "data": { "$push": { "k": { "$toString": "$serie._id" }, "v": "$serie" }} }}, { "$replaceRoot": { "newRoot": { "$arrayToObject": "$data" }}}])