jcardoso
jcardoso

Reputation: 61

change key document mongodb aggregate

would be possible with an aggregate. I change the key of the object to the _id of it. I'm trying to do with map-reduce in aggregation with project. Any idea? what I have:

{"serie" : {
    "_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" : [],
}}

How I'm trying to leave:

{"5a55f988b6c9dd15b47faa2a" : {
       "updatedAt" : ISODate("2018-02-09T13:22:54.521Z"),
       "createdAt" : ISODate("2018-01-10T11:31:20.978Z"),
       "deletar" : false,
       "infantil" : false,
       "status" : true,
       "turma" : []
}}

Upvotes: 2

Views: 1880

Answers (3)

Ashh
Ashh

Reputation: 46441

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

Upvotes: 1

s7vr
s7vr

Reputation: 75914

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

Upvotes: 1

mickl
mickl

Reputation: 49945

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", ... }

Upvotes: 2

Related Questions