Search code examples
mongodbmongoosemongodb-querymongoose-schema

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 ?


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