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

159
Views
mongodb aggregate two collections and add new fields

I have two collections: authors and books

author example:

{
   _id: "605f6746c114544ee04228bd"
   firstName: "firstName",
   lastName: "lastName",
}

book example:

{
   _id: "605f6746c114544ee04228bd"
   title: "title",
   pages: 350,
}

I want to get the list of books with thier author firstName and lastName.

here is my current code:

let books;

books = await Book.find();
books.forEach(async (book, i) => {
  const author = await Author.findOne(
    { _id: book.authorId },
    { firstName: 1, lastName: 1, _id: 0 }
  );
  books[i].authorFirstName = author.firstName;
  books[i].authorLastName = author.lastName;
});

This is not a good practice because for each book I execut another request to mongodb database! Any better solution?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Mongoose version to join two models with relationship

books = await Book.find({}).populate({ path:"authorId", select:{firstName:1, lastName:1}})

Using aggregation

let books = await Book.aggregation([
   { 
     $lookup:{
        from:"collection_of_author",
        localField: "authorId",
        foreignField: "_id",
        as: "author"
     }
   },
  {
    $unwind: {
       path:"authorId",
       preserveNullAndEmptyArrays:true 
    }
  }])
over 4 years ago · Santiago Trujillo Report

0

Clean code and higher performance using mongoose populate

  import Book from "../models/Book";
  import Author from "../models/Author";

  let books = await Book.find().populate({
    path: "authorId",
    model: Author,
    select: { firstName: 1, lastName: 1, _id: 0 },
  });
over 4 years ago · Santiago Trujillo 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!