0
{
    "_id" : ObjectId("62622dd73905f04f59db2971"),
    "array1" : [ 
        {
            "_id" : "12",
            "array2" : [ 
                {
                    "_id" : "123",
                    "answeredBy" : []
                }, 
                {
                    "_id" : "124",
                    "answeredBy" : []
                }
            ]
        }
    ]
}

/* 2 */
{
    "_id" : ObjectId("626230e03905f04f59db29f5"),
    "array1" : [ 
        {
            "_id" : "22",
            "array2" : [ 
                {
                    "_id" : "223", //compare this
                    "answeredBy" : []
                }, 
                {
                    "_id" : "220", // and this
                    "answeredBy" : []
                }
            ]
        }
    ]
}

I am trying to compare array2 zero index _id with one index _id

My query is

db.getCollection('nestedArray').find({$expr:{$gt:['$array1.array2.0._id','$array1.array2.1._id']}})

showing zero records

1 Answer 1

1

Use $arrayElemAt

db.collection.find({
  $expr: {
    $gt: [
      {
        $arrayElemAt: [ { $arrayElemAt: [ "$array1.array2._id", 0 ] }, 0 ]
      },
      {
        $arrayElemAt: [ { $arrayElemAt: [ "$array1.array2._id", 0 ] }, 1 ]
      }
    ]
  }
})

mongoplayground


If you use index, it is a different situation. Check mongoplayground below.

db.collection.find({
  $expr: {
    $gt: [
      "$array1.0.array2.0._id",
      "$array1.0.array2.1._id"
    ]
  }
})

mongoplayground

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

1 Comment

Explanation would be helpful, not understandable how this works..

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.