【问题标题】:Query filteration in MongoDBMongoDB中的查询过滤
【发布时间】:2021-02-21 10:43:00
【问题描述】:

我有一个包含以下详细信息的产品列表:

"products": [{
    "product_name": "A",
    "product_type": [{
        "name": "Metal"
      },
      {
        "name": "Wood"
      },
      {
        "name": "Carbon"
      }
    ],
  },
  {
    "product_name": "B",
    "product_type": [{
        "name": "Metal"
      },
      {
        "name": "Iron"
      }
    ],
  },
  {
    "product_name": "C",
    "product_type": [{
        "name": "Metal"
      },
      {
        "name": "Wood"
      }
    ],
  },
  {
    "product_name": "D",
    "product_type": [{
      "name": "Wood"
    }],
  }
]

我想过滤这个集合

Product.find(query)

在哪里发送 query = ["Wood", "Carbon"] 应该列出我具有 WoodCarbon 类型的产品。

或者像这样工作:

Product.find({product_type: [ { name: query } ]}) list me products with name A, C and D

【问题讨论】:

    标签: node.js mongodb mongoose mongodb-query


    【解决方案1】:

    您可以使用dot notation$in 来解决您的问题:

    Product.find({
      "product_type.name": {
        $in: ["Wood", "Carbon"]
      }
    })
    

    MongoPlayground

    【讨论】:

      【解决方案2】:

      你可以写这样的查询,

      Product.find({product_name:{$in: [ 'A', 'C', 'D']}}) list me products with name A, C and D
      
      

      或者如果你想根据product_type查找文档,那么你可以使用以下查询

      Product.find({
        "product_type.name": {
          $in: [
            "Metal"
          ]
        }
      })
      

      参考:https://mongoplayground.net/p/vSfkpUjU494

      【讨论】:

        猜你喜欢
        • 2021-03-19
        • 2019-11-24
        • 1970-01-01
        • 2012-03-27
        • 1970-01-01
        • 2018-03-22
        • 2018-02-04
        • 2017-09-08
        • 1970-01-01
        相关资源
        最近更新 更多