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

183
Views
How to index a collection with documents that contain field with an array of object Id

I have a table like this

person = {
    name : String,
    favoriteFoods : [{type:Schema.Types.ObjectId, ref:'Food'}]
}

Q1: I would like to do the searching fast when I search for person with particular favourite food.

May I know if it is possible to index the favoriteFoods field and how to do it?

Q2: Alternatively, I would like to populate the favoriteFoods fields with Food content when I get back the person documents. May I know if there is command to do so?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Yes, you can index an array field. It's what's called a multikey index but in reality it's basically creating a normal index. Behind the scenes Mongo flattens the array and builds a separate index for each element.

For Q2 the easiest way to "populate" documents in Mongo is by using $lookup stage while aggregation, like so:

db.person.aggregate([
  {
    $match: {
      name: "tom"
    }
  },
  {
    "$lookup": {
      "from": "foods",
      "localField": "favoriteFoods",
      "foreignField": "_id",
      "as": "favoriteFoods"
    }
  }
])

Mongo Playground

However if you first fetch the document you can just do a second db call to the other collection to populate your field, this is how mongoose does it for example with their populate option.

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!