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

Only using find method in mongo to limit filter age

I have the following BSON data:

[
  {
    "test": 1,
    "arr": [
      {
        age: 24,
        name: "a"
      },
      {
        age: 55,
        name: "b"
      },
      {
        age: 12,
        name: "c"
      },
      {
        age: 14,
        name: "d"
      },
      {
        age: 67,
        name: "e"
      }
    ]
  }
]

Is it possible by using only "find" method I get the output in a way that the "age" field inside "arr" array is less than 30 for each array element?.
So My expected output:

[
  {
    "test": 1,
    "arr": [
      {
        age: 24,
        name: "a"
      }
      {
        age: 12,
        name: "c"
      },
      {
        age: 14,
        name: "d"
      }
    ]
  }
]

If also it is possible with one find to flatten the array that would be great too.

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

Explained in the above.

>Solution :

You can use the $filter operator to filter the element(s) in an array in the projection.

db.collection.find({
  "arr.age": {
    $lt: 30
  }
},
{
  "test": 1,
  "arr": {
    $filter: {
      input: "$arr",
      cond: {
        $lt: [
          "$$this.age",
          30
        ]
      }
    }
  }
})

Demo @ Mongo Playground

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