Home > front end >  comparing two fields in a nested array
comparing two fields in a nested array

Time:04-22

{
    "_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

CodePudding user response:

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

  • Related