0

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.

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.