【问题标题】:MongoDB Atlas Search by referenced document field search termMongoDB Atlas 按引用的文档字段搜索词搜索
【发布时间】:2020-06-20 20:26:43
【问题描述】:

我知道如何使用 MongoDB Atlas search 按名称和给定的买家 ID 以及已知的/matched 供应商名称来搜索订单 例如:

(使用猫鼬 ODM)

    const searchResults = await Order.aggregate([
    {
      $search: {
        text: {
          query: '{search-term}',
          path: 'name',
          fuzzy: {
            maxEdits: 2,
            maxExpansions: 100,
          },
        },
      },
    },
    { $unwind: '$supplier' },
    {
      $lookup: {
        from: 'suppliers',
        localField: 'supplier',
        foreignField: '_id',
        as: 'suppliers',
      },
    },
    {
      $match: {
        buyer: mongoose.Types.ObjectId('5e19a594c86e72017debf9dc'),
        // The search term entered by a user:
        'suppliers.name': 'supplierName',
      },
    },
  ]);

但是,我希望能够利用 MongoDB Atlas 搜索来:

  • 搜索所有订单,
  • 给定一个Buyer ID,
  • 其中搜索词 - 可能不是完全匹配 - 是 Supplier name,
  • Buyer 和 Supplier 按引用的 ID 嵌套在 Order 上:

拥有Order 架构:

const orderSchema = new mongoose.Schema({
  name: {
    type: String,
    minlength: 2,
    maxlength: 255,
  },
  buyer: { type: ObjectId, ref: 'Buyer' },
  supplier: { type: ObjectId, ref: 'Supplier' },
});

Buyer 架构:

const buyerSchema = new mongoose.Schema({
  name: {
    type: String,
  },
  ...
});

Supplier 架构:

const supplierSchema = new mongoose.Schema({
  name: {
    type: String,
  },
  ...
});

【问题讨论】:

    标签: mongoose mongodb-atlas mongodb-atlas-search


    【解决方案1】:

    这应该可以在$search 中使用compound、text 和equals:

    const order = await Order.aggregate([
    { $search: {
        compound: {
            must: [ 
                { text: { query: "SEARCH TERM", path: "name"}}, 
                { equals: { path: "buyer", value: ObjectId("5e19a594c86e72017debf9dc") }} 
            ]
        }
    }}])
    

    如果您不希望它影响您的评分,您也可以将 equals 查询移至过滤子句。

    【讨论】:

      【解决方案2】:

      我已经设法通过以下方法实现了所需的结果,但它不使用 Atlas Search,因此我将不胜感激有关如何做到这一点的任何进一步帮助。

      const order = await Order.aggregate([
            { $unwind: '$supplier' },
            {
              $lookup: {
                from: 'suppliers',
                localField: 'supplier',
                foreignField: '_id',
                as: 'suppliers',
              },
            },
            {
              $match: {
                buyer: mongoose.Types.ObjectId('5e19a594c86e72017debf9dc'),
                'suppliers.name': new RegExp('^' + supplierName, 'i'),
              },
            },
          ]);
      

      【讨论】:

        猜你喜欢
        • 2016-11-23
        • 2023-03-28
        • 2021-06-22
        • 1970-01-01
        • 1970-01-01
        • 2020-07-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多