Home > Mobile >  How can II take out from _id, mean looking for to unwind object having dynamic keys in mongodb, othe
How can II take out from _id, mean looking for to unwind object having dynamic keys in mongodb, othe

Time:06-23

I had shared original collection example, current my output, and expected output. with link of mongo playground. original collection:

[
  {
    "_id": "foo1",
    "1": {
      "bar": 6
    },
    "0": {
      "bar": 11
    },
    "3": {
      "bar": 8
    },
    "2": {
      "bar": 0
    },
    "5": {
      "bar": 8
    },
    "4": {
      "bar": 19
    },
    "6": {
      "bar": 8
    }
  },
  {
    "_id": "foo2",
    "1": {
      "bar": 18
    },
    "0": {
      "bar": 3
    },
    "3": {
      "bar": 19
    },
    "2": {
      "bar": 0
    },
    "5": {
      "bar": 13
    },
    "4": {
      "bar": 17
    },
    "7": {
      "bar": 8
    },
    "6": {
      "bar": 8
    },
    "8": {
      "bar": 8
    }
  },
  {
    "_id": "foo3",
    "1": {
      "bar": 0
    },
    "0": {
      "bar": 2
    },
    "3": {
      "bar": 18
    },
    "2": {
      "bar": 2
    },
    "4": {
      "bar": 12
    }
  }
]

current output is

[
  {
    "_id": {
      "2": 2
    }
  },
  {
    "_id": {
      "5": 21
    }
  },
  {
    "_id": {
      "4": 48
    }
  },
  {
    "_id": {
      "8": 8
    }
  },
  {
    "_id": {
      "1": 24
    }
  },
  {
    "_id": {
      "0": 16
    }
  },
  {
    "_id": {
      "3": 45
    }
  },
  {
    "_id": {
      "7": 8
    }
  },
  {
    "_id": {
      "6": 16
    }
  }
]

expected output

[
  {
    "2": 2
  },
  {
    "5": 21
  },
  {
    "4": 48
  },
  {
    "8": 8
  },
  {
    "1": 24
  },
  {
    "0": 16
  },
  {
    "3": 45
  },
  {
    "7": 8
  },
  {
    "6": 16
  }
]

link of example: https://mongoplayground.net/p/Eh9psmEhgIk

I am junior developer, I had tried with other ways, but I am stuck in middle, I request please help me to explore this exercise. How can I improve better or other way that I can achieve my expected output.

CodePudding user response:

You are missing only one step: $replaceRoot

 {$replaceRoot: {newRoot: "$_id"}}

See how it works on the playground example

CodePudding user response:

Maybe something like this:

{
 "$replaceRoot": {
  "newRoot": "$_id"
}
}

Playground

  • Related