skip to Main Content

Here is my Data in DB

{
name: abc
    pro: 1
    },
    {
    name:cde,
    pro: 2
    },
    {
name:fgh,
    pro:3
    },
    {
name:ijk,
    pro:4
    },

here is my query to aggregate the result I’ve successfully get the count of name and pro:

db.aggregate([
        {
          $facet: {
           
            "name": [
              { $group: { _id: '$name', N: { $sum: 1 } } }
            ],
},{ $project: {  "pro": {
              $map: {
                input: '$pro',
                in:{ $arrayToObject: [[{ k: '$$this._id', v: '$$this.N'}]] }
              }
            },
}}])

For pro which is 1 in DB but against 1, I want to map a etc, in response.

Expecting Output:

{
        name: abc
        pro: a //value in DB is 1.
        },
        {
        name:cde,
        pro: b //value in DB is 2.
        },
        {
        name:fgh,
        pro:c //value in DB is 3
        },
        {
        name:ijk,
        pro:d //value in DB is 4
        },
}

2

Answers


  1. If I understand your question correctly, you need to map pro integer values to corresponding characters. Then this should work:

    db.collection.aggregate([
      {
        $project: {
          _id: 0,
          name: 1,
          pro: {
            $slice: [
              [
                "",
                "a",
                "b",
                "c",
                "d"
              ],
              "$pro",
              1
            ]
          }
        }
      },
      {
        "$unwind": "$pro"
      }
    ])
    

    Here is the playground link.

    Login or Signup to reply.
  2. Use Map pro function, it will works

    db.collection.aggregate([
    {
    $project: {
      _id: 0,
      name: 1,
      pro: {
        $slice: [
          [
            "",
            "a",
            "b",
            "c",
            "d"
          ],
          "$pro",
          1
        ]
      }
    }
    },
    {
     "$unwind": "$pro"
    }
    ])
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search