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

Viewed 124

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?

1 Answers

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.

Related