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

Mongoose return all documents that contain a value wherever inside a property

Lets say my documents look like this :


  _id: "6285e9a7aff93ead37ec50ad",
  date: "2022-04-28T10:51:37.923Z",
  devices: {
    tablets: [
      {
        brand: "samsung",
        model: "s20"
      },
      {
        brand: "samsung",
        model: "s21"
      },
      {
        brand: "apple",
        model: "ipad_mini"
      },
    ],
    phones: [
      {
        brand: "samsung",
        model: "galaxy_s20"
      },
      {
        brand: "samsung",
        model: "galaxy_s20_lite"
      }
    ],
    laptops: []
  }
}

how would i query and return all documents that contain at least an "apple" value in "brand" property wherever inside the "devices" property ?

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

>Solution :

When you have more dynamic keys, you can use

db.collection.aggregate([
  {
    $project: {
      "d": {
        "$objectToArray": "$devices"
      }
    }
  },
  {
    "$match": {
      "d.v.brand": "apple"
    }
  }
])

You need to restructure the data if required. It returns if there is atleast one match.

playground

db.collection.aggregate([
  {
    $project: {
      "d": {
        "$objectToArray": "$devices"
      }
    }
  },
  {
    "$match": {
      "d.v.brand": "apple"
    }
  },
  {
    "$project": {
      "devices": { //To reshape back
        "$arrayToObject": "$d"
      }
    }
  }
])

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