Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

188
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda