Mongoose return 所有在 属性 中包含值的文档

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

假设我的文档是这样的:


  _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: []
  }
}

我将如何查询 return 在 "brand" 属性 任何地方 中至少包含一个 "apple" 值的所有文档在 "devices" 属性 内 ?

当你有更多的动态键时,你可以使用

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

如果需要,您需要重组数据。它 returns 如果至少有一个匹配项。

playground

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

Playground