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

112
Views
MongoDB get last updated set of documents of each category

I have this document structure:

{
 ...,
insertionDate: 'someDate',
product: 'cool jacket',
color: 'red',
store: 'north store',
}

The thing is this collection stores every change a product has ever had. At this moment I have the following code to retrieve all the products in one store with one color of a set previously defined.

const colors = ['red', 'blue', 'orange'];    
collection.find({$and: [{store: store)}, {color: {$in: colors}}]});

The problem is that I get all the historical data, for example I can get 'cool jacket' in each color 4 times, because it appears multiple times in the database with different insertionDate.

How do I get the last insertionDate of each product?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Here is a tested code:

await Collection.aggregate([
    {
      $match: {
        color: { $in: colors }
      }
    },
    { $sort: { insersionDate: -1 } },
    { $group: { _id: '$product', doc: { $first: '$$ROOT' } } }
  ]);
about 4 years ago · Juan Pablo Isaza Report

0

You can achieve this using aggregate query with three pipelines.

  1. $match to match the desired store and colors.

  2. Use $sort to sort by insertionDate desc order.

  3. $group to group by product Name or product Id. While grouping $first accumulator will help to get the recent inserted product.

about 4 years ago · Juan Pablo Isaza Report

0

You can use collection.find({$and: [{store: store)}, {color: {$in: colors}}]}).sort(insertionDate: -1) will sort them according to the last inserted date.

about 4 years ago · Juan Pablo Isaza Report
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!