Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

293
Views
Elasticsearch 7.1: Convert mongodb aggregation pipeline to elastic search query

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"
      }
    ]
  }
]
over 4 years ago · Santiago Trujillo
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!