Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to check in mongodb aggregation that document has key which is an array whose second element exists or not?

I have mongodb document it has key which is an array. i want to check that the 2nd element in array exists or not. if exists then return the documents otherwise return no document.

example document :

{
 _id : "672d75267",
 name : "somename",
 arr : [1,2,3]
}


db.collection.aggregate([
 {
   $match : {
      $expr : {
        $arrayElemAt : ["$arr",2]
     }
   }
 }
])

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Array index start from 0 that is why we have taken "arr.1"

db.collection.aggregate([
  {
    $match: {
      "arr.1": {
        "$exists": true
      }
    }
  },
])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading