Home > Blockchain >  Map array result in mongodb aggregation
Map array result in mongodb aggregation

Time:04-11

I have the following MongoDB query:

const vaccination = await Schedule.aggregate([
        { $match: { status: ScheduleStatus.Published } },
        { "$unwind": { "path": "$vaccines", "preserveNullAndEmptyArrays": true } },

        {
            "$group": {
                "_id": "$vaccines.vaccine",
                "count": { "$sum": "$vaccines.stok" },

            }
        },
        {
            $lookup: { from: 'vaccines', localField: '_id', foreignField: '_id', as: 'vaccine' },
        },
        {
            $project: {

                "count": 1,
                "vaccine": { "$arrayElemAt": ["$vaccine.name", 0] }


            }
        }

    ]);

and return the following results :

[
    {
        "_id": "61efd8a812432135c08a748d",
        "count": 20,
        "vaccine": "Sinovac"
    }
]

is there a way I can make the output to be an array of values like:

[["Sinovac",20]]

Thanks sorry for my bad english

CodePudding user response:

So you can't get the exact structure you asked for, by definition the aggregation framework returns an array of "documents", a document is in the form of {key: value}, What you can do however is return the following structure:

[
  {
    "values": [
      "61efd8a812432135c08a748d",
      20,
      "Sinovac"
    ]
  }
]

With this pipeline:

db.collection.aggregate([
  {
    $project: {
      _id: 0,
      values: {
        $map: {
          input: {
            "$objectToArray": "$$ROOT"
          },
          as: "item",
          in: "$$item.v"
        }
      }
    }
  }
])

Mongo Playground

  • Related