MongoDB 按参考文档字段搜索词进行图集搜索

MongoDB Atlas Search by referenced document field search term

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

(使用 Mongoose 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 搜索来:

具有 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,
  },
  ...
});

我已经通过以下方法获得了所需的结果,但它没有使用 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'),
        },
      },
    ]);

这应该可以在 $search 中使用 compound, text and equals:

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

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