Home > Mobile >  MongoDB - Check if an array match certain condition
MongoDB - Check if an array match certain condition

Time:10-17

Sample documents:

[
  {
      "_id" : ObjectId("634c5167d7f84b95b91f9ba2"),
      "activity_id" : ObjectId("634c5167d7f84b95b91f9b9f"),
      "lat" : 39.9762,
      "lon" : 116.330383333333,
      "altitude" : 229.658792650919,
      "date_days" : 39184.4329166667,
      "date_time" : ISODate("2007-04-12T10:23:24.000 0000"),
      "altitudes" : [
          173.884514435696,
          229.658792650919
      ]
  },
  {
      "_id" : ObjectId("634c5167d7f84b95b91f9ba3"),
      "activity_id" : ObjectId("634c5167d7f84b95b91f9b9f"),
      "lat" : 39.9760333333333,
      "lon" : 116.330366666667,
      "altitude" : 259.186351706037,
      "date_days" : 39184.4341319444,
      "date_time" : ISODate("2007-04-12T10:25:09.000 0000"),
      "altitudes" : [
          229.658792650919,
          259.186351706037
      ]
  }
]

Here, what I need is to check if the altitudes field has two elements and if the second one is greater than the first.

So far what I have done:

$match: {
    $and: [
        { 'altitudes': { $size: 2 } },
        { 'altitudes.1': { $gt: 'altitudes.0' } }
    ]
}

Also:

$match: {
    $and: [
        { 'altitudes': { $size: 2 } },
        { 'altitudes': { 'altitudes.1': { $gt: 'altitudes.1' } } }
    ]
}

Also:

$match: {
    $and: [
        { 'altitudes': { $size: 2 } },
        { 'altitudes': {  $gt: [ 'altitudes.1', 'altitudes.0' ] } }
    ]
}

Nothing seems like working, though $size does actually work. For reference, I am following Array operatons.

Yes, I have written db.collection.aggregate. That's not the main part, so decided not to share.

Any help or suggestions.

CodePudding user response:

Work with $expr operator.

Use $arrayElemAt to get the element from the array by index.

db.collection.aggregate([
  {
    $match: {
      $expr: {
        $and: [
          {
            $eq: [
              {
                $size: "$altitudes"
              },
              2
            ]
          },
          {
            $gt: [
              {
                $arrayElemAt: [
                  "$altitudes",
                  1
                ]
              },
              {
                $arrayElemAt: [
                  "$altitudes",
                  0
                ]
              }
            ]
          }
        ]
      }
    }
  }
])

Demo @ Mongo Playground

  • Related