Home > Software engineering >  Unable to match objects in array
Unable to match objects in array

Time:11-20

I have several documents like the following and I'm trying to retrieve the documents where the first element of the scores array was created within the past 24hrs:

[
  {
    "id": 1,
    "scores": [
      {
        "score": 1,
        created_at: ISODate("2022-11-19T00:05:00.000 00:00")
      },
      {
        "score": 2,
        created_at: ISODate("2022-11-20T00:05:00.000 00:00")
      }
    ]
  },
  {
    "id": 2,
    "scores": [
      {
        "score": 3,
        created_at: ISODate("2022-11-20T00:05:00.000 00:00")
      },
      {
        "score": 5,
        created_at: ISODate("2022-11-20T00:05:00.000 00:00")
      }
    ]
  },
]

This is the query:

db.collection.aggregate([
  {
    $match: {
      $expr: {
        $gte: [
          "$scores.0.created_at",
          {
            $subtract: [
              "$$NOW",
              86400000
            ]
          }
        ]
      }
    }
  }
])

https://mongoplayground.net/p/L1jI10efWGL

However, nothing is returned. Does anyone know what might be wrong?

CodePudding user response:

Instead of using $scores.0.created_at, use $getField to get the value of created_at from the first element of the scores array.

db.collection.aggregate([
  {
    $match: {
      $expr: {
        $gte: [
          {
            $getField: {
              field: "created_at",
              input: {
                $first: "$scores"
              }
            }
          },
          {
            $subtract: [
              "$$NOW",
              86400000
            ]
          }
        ]
      }
    }
  }
])

Demo @ Mongo Playground

  • Related