skip to Main Content

I have something like this.

{
  "priceDetails": [
    {
      "cities": [
        {
          "cityId": "64a297a8bb1dc440ccef6c3c",
          "name": "Bhopal",
          "prices": "1200",
          "commissionType": "PERCENTAGE",
          "commissionValue": "20",
          "_id": "64a2990b344e735476fb54ca"
        }
      ]
    }
  ]
}

Need something like this.

{
  "priceDetails": {
    "cityId": "64a297a8bb1dc440ccef6c3c",
    "name": "Bhopal",
    "prices": "1200",
    "commissionType": "PERCENTAGE",
    "commissionValue": "20",
    "_id": "64a2990b344e735476fb54ca",
  }
}

I tried $unwind, but it uses a lot of database processing power to filter and retrieve the data.

I’m using node v18.7.0 & mongo version v4.4

I’m baffled at this point, any help would be greatly appreciated. Cheers!

2

Answers


  1. One option is to use a simple projection:

    db.collection.find(
      {},
      {
        _id: 0,
        priceDetails: {$first: "$priceDetails.cities"}
      }
    )
    

    See how it works on the playground example

    Login or Signup to reply.
  2. In your present pipeline for aggregating data, you can utilise $set and $arrayElemAt.

    To modify the response, use $set, and to retrieve an element from an array, use $arrayElemAt.

    {
      $set: {
        priceDetails: {
          $arrayElemAt: [
            {
              $arrayElemAt: ["$priceDetails.cities", 0]
            },
            0
          ]
        }
      }
    }
    

    The first index of the array will be set by inner $arrayElemAt. in the outer array’s 0 index. The outer $arrayElemAt will then act in a manner similar to that of the inner $arrayElemAt.

    Consult the document for more details.

    $set : https://www.mongodb.com/docs/manual/reference/operator/update/set/#definition

    $arrayElemAt : https://www.mongodb.com/docs/manual/reference/operator/aggregation/arrayElemAt/

    I hope that this may be useful to you or someone else.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search