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

MongoDB Compass: Filter query on array object is not working

I want to filter the array object based on value provided.
I am using following query in Filter text box and along with projection. Seems like there filter is not getting applied.

I also tried following but unfortunately array is not getting filtered

  { MissingPersonIds : {$elemMatch: { PhotoId : '2 - Copy (3).jpg'}} }

enter image description here

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

Filter:

{ "MissingPersonIds.PhotoId" : "2 - Copy (3).jpg" }

Projection:

{ MissingPersonIds : { $slice: [1,10] }}

Schema is:

[{
  "_id": {
    "$oid": "61ada7da9a30fd8471869bbc"
  },
  "ImportKeyId": 5843,
  "MissingPersonIds": [
    {
      "PhotoId": "2 - Copy.jpg",
      "Description": "Account ID not found"
    },
    {
      "PhotoId": "2 - Copy (2).jpg",
      "Description": "Account ID not found"
    },
    {
      "PhotoId": "2 - Copy (3).jpg",
      "Description": "Account ID not found"
    },
    {
      "PhotoId": "2 - Copy - Copy.jpg",
      "Description": "Account ID not found"
    },
    {
      "PhotoId": "2 - Copy - Copy (2).jpg",
      "Description": "Account ID not found"
    }
  ]
}]

The output I am expecting is :

[{
  "_id": {
    "$oid": "61ada7da9a30fd8471869bbc"
  },
  "ImportKeyId": 5843,
  "MissingPersonIds": [
    {
      "PhotoId": "2 - Copy (3).jpg",
      "Description": "Account ID not found"
    }
  ]
}]

>Solution :

You need $filter in the projection to filter element(s) in an array.

db.collection.find({},
{
  "MissingPersonIds": {
    $filter: {
      input: "$MissingPersonIds",
      cond: {
        "$eq": [
          "$$this.PhotoId",
          "2 - Copy (3).jpg"
        ]
      }
    }
  }
})

Sample 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