3

This is my first time using elastic search so bear with me. I have two schemas, Offers Schema and Offer Comment Schema, I need to search by offer title and have each offer result with its comments

Offer Schema:

{
    title: {
        type: String,
        es_indexed: true,
    }
}

In the above offer schema, there is no field to reference offer comments

Offer Comment Schema:

{
    offer: {
      type: Schema.Types.ObjectId,
      ref: 'Offer',
      es_indexed: true,
    },
    comment: {
      type: String,
      es_indexed: true,
    }
}

In the above offer comment schema, offer field reference the offer which the comment belongs to. The following aggregation pipeline is used to achive the desired output via mongodb driver.

Mongodb aggregation pipeline done on offers collection:

[
  {
    $lookup: {
      from: 'offercomments',
      let: {
        id: '$_id',
      },
      pipeline: [
        {
          $match: {
            $expr: {
              $and: [
                {
                  $eq: ['$offer', '$$id'],
                },
              ],
            },
          },
        },
        {
          $sort: {
            createdAt: -1,
          },
        },
        {
          $limit: 1,
        },
      ],
      as: 'comments',
    },
  },
];

here are some output samples from the aggregation pipeline

Aggregation output sample:

[
  {
    "_id": "123",
    "title": "offer title sample",
    "comments": [
      {
        "_id": "_123",
        "offer": "123",
        "comment": "Hello there"
      }
    ]
  },
  {
    "_id": "456",
    "title": "offer title sample",
    "comments": [
      {
        "_id": "_456",
        "offer": "456",
        "comment": "Hello there"
      }
    ]
  }
]

0 Answers0