Home > other >  Query an Array of Objects to return the exact match if not return the previous value
Query an Array of Objects to return the exact match if not return the previous value

Time:11-17

My collection

[
  {
    "_id": "value",
    "data": [
      {
        "d": "2022-05-16",
        "v": 10.06
      },
      {
        "d": "2022-05-18",
        "v": 9.11
      },
      {
        "d": "2022-05-20",
        "v": 7.06
      }
    ],
    "name": "Vegeta"
  }
]

Now I want to make a query say

{name : "something" , "data.d" : "2022-05-18"} --> this filter returns v = 9.11
{name : "something" , "data.d" : "2022-05-17"} --> this filter also should return v = 10.06
{name : "something" , "data.d" : "2022-05-19"} --> this filter also should return v = 9.11

Basically I want to the return the result from data which matches the given date if not present then return the previous date data.

I have tried using elemmatch. Unwind works for me but need to increase the performance of the query.If possible can we do in the mongo shell itself.

CodePudding user response:

db.collection.aggregate([
  {
    $match: {
      "name": "Vegeta"  //input
      
    }
  },
  {
    "$project": {
      "_id": 1,
      "name": 1,
      "data": {  //filter the array elements
        "$filter": {
          "input": "$data",
          "as": "data",
          "cond": {
            "$lte": [
              "$$data.d",
              "2022-05-20"  //input
              
            ]
          }
        }
      }
    }
  },
  {
    $project: {
      "_id": 1,
      "name": 1,
      "data": {  //sort the remaining array elements
        $sortArray: {
          input: "$data",
          sortBy: {
            "d": -1
          }
        }
      }
    }
  },
  {
    $project: {
      "_id": 1,
      "name": 1,
      "data": {  //pick one
        "$arrayElemAt": [
          "$data",
          0
        ]
      }
    }
  }
])

Mongo Playground

  • Related