Home > OS >  MongoDB 5 version Aggregation convert to 4.4 version
MongoDB 5 version Aggregation convert to 4.4 version

Time:09-15

I have the following aggregation that is supported by MongoDB 5 but not 4.4. How can I write this in v4.4?

Aggregation Pipeline (V5):

 "$ifNull": [
                    {
                      "$getField": {
                        "field": "prices",
                        "input": {
                          "$first": "$matchedUsers"
                        }
                      }
                    },
                    []
                  ]

Here's a MongoDB Playground for the same.

CodePudding user response:

This pipeline should work in version 4.4:

db.datasets.aggregate([
  {
    "$lookup": {
      "from": "users",
      "localField": "assignedTo",
      "foreignField": "id",
      "as": "matchedUsers"
    }
  },
  {
    "$addFields": {
      "cgData": {
        "$first": "$matchedUsers"
      }
    }
  },
  {
    "$addFields": {
      "cgData": {
        "$first": {
          "$filter": {
            "input": {
              "$ifNull": [
                "$cgData.prices",
                []
              ]
            },
            "as": "currentPrice",
            "cond": {
              "$and": [
                {
                  "$gte": [
                    "$firstBillable",
                    "$$currentPrice.beginDate"
                  ]
                },
                {
                  $or: [
                    {
                      $eq: [
                        {
                          $type: "$$currentPrice.endDate"
                        },
                        "missing"
                      ]
                    },
                    {
                      "$lt": [
                        "$firstBillable",
                        "$$currentPrice.endDate"
                      ]
                    }
                  ]
                }
              ]
            }
          }
        }
      }
    }
  },
  {
    "$addFields": {
      cgPrice: "$cgData.price"
    }
  },
  {
    "$project": {
      cgData: 0,
      "matchedUsers": 0
    }
  }
])

In this, a new $addFields stage is added, to get first element of matchedUsers array.

  {
    "$addFields": {
      "cgData": {
        "$first": "$matchedUsers"
      }
    }
  }

Then we use $ifNull like this:

{
   "$ifNull": [
          "$cgData.prices",
          []
        ]
}

See it working here.

  • Related