skip to Main Content

I have a Mongo collection as such:

db.items.find({}):

[{
  "_id": {
    "$oid": "64e929386a2bff904d86118a"
  },
  "name": "Copies",
  "legacy_id": 181
},
{
  "_id": {
    "$oid": "64e929386a2bff904d86118b"
  },
  "name": "Temp",
  "legacy_id": 182
},
{
  "_id": {
    "$oid": "64e929386a2bff904d86118c"
  },
  "name": "Test",
  "legacy_id": 183
}]

Is there a way to combine the data to have a single document that contains the key/value pairs of the "_id": "legacy_id" of the returned query results? A result like below would work fine for me. I know I can do this after the fact through some code but I’m wondering if there is a way to do this in the aggregate pipeline. Here’s the end result that I would like to achieve:

[{
  "64e929386a2bff904d86118a": 181,
  "64e929386a2bff904d86118b": 182,
  "64e929386a2bff904d86118c": 183,
}]

2

Answers


  1. Perform unconditional $group to $push all k-v tuples of records into an array first. Then use $arrayToObject to convert the array into object.

    db.collection.aggregate([
      {
        "$group": {
          "_id": null,
          "records": {
            "$push": {
              k: {
                "$toString": "$_id"
              },
              v: "$legacy_id"
            }
          }
        }
      },
      {
        "$replaceRoot": {
          "newRoot": {
            "$arrayToObject": "$records"
          }
        }
      }
    ])
    

    Mongo Playground

    Login or Signup to reply.
  2. you can use $arrayToObject and using $replaceRoot you can make it root

    test it here: mongo playgroung

    db.collection.aggregate([
      {
        $replaceRoot: {
          newRoot: {
            $arrayToObject: [
              [
                {
                  k: "$_id",
                  v: "$legacy_id"
                }
              ]
            ]
          }
        }
      }
    ])
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search