【问题标题】:MongoDB Query Nested SchemaMongoDB 查询嵌套模式
【发布时间】:2021-06-29 18:18:30
【问题描述】:

我有下一个模式:

产品架构:

_id: String
name: String
description: String
company: Company

公司架构:

_id: String
name: string

我正在尝试查找与我的查询字符串匹配的名称或公司名称的所有产品。

我已经试过了:

const query: any[] = [
  {
    "company.name": {
      $regex: name,
      $options: "i",
    },
  },
  {
    "name": {
      $regex: name,
      $options: "i",
    },
  }
];

return Product.find()
  .or(query)
  .populate("company")

数据 - 产品:

{ _id: "6067b7d7b5913759d9bb8b39", "name": "Test 1", "description": "Desc", "company": "6067b809c78a4a39ebeae4d4" }

数据 - 公司:

{ _id: "6067b809c78a4a39ebeae4d4", "name": "Facebook" }, 
{ _id: "59862209c78a4a39ebeae4d4", "name": "Apple" },

【问题讨论】:

    标签: javascript node.js mongodb mongoose nosql


    【解决方案1】:

    此查询将仅过滤产品,不适用于您的情况,因为您还想通过 company.name 过滤

    Product.find()
      .or(query)
      .populate("company")
    

    演示 - https://mongoplayground.net/p/VqREj1vvkss

    使用聚合查询来实现这一点

    db.companies.aggregate([
      { $lookup: { "from": "products", "localField": "_id",  "foreignField": "company",  "as": "products"} },
      { $unwind: "$products" },
      { $match: {
        $or: [
            { "name": { $regex: "Test 1",$options: "i", }, },
            { "products.name": { $regex: "Test 1",$options: "i" } }
        ]}
      }
    ])
    

    https://mongoosejs.com/docs/api/aggregate.html#aggregate_Aggregate

    【讨论】:

      猜你喜欢
      • 2021-01-31
      • 1970-01-01
      • 2021-06-20
      • 2015-05-20
      • 1970-01-01
      • 1970-01-01
      • 2017-09-21
      • 1970-01-01
      • 2013-06-22
      相关资源
      最近更新 更多