Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to index a document in mongoDB populating its references?

If I have these two collections:

Book: {
title: String,
description: String
author: {type: mongoose.Schema.Types.ObjectId, ref: 'User'},
}

User: {
_id: (generated by mongo)
username: String
}

And I want to index Book for FTS. Can I do it in such a way that it will also be searchable by username even though the usernames are not explicitly stored in the books collection?

In other words, is it possible (or advisable) to index a populated collection?

Thanks

like image 884
Michael Seltenreich Avatar asked Dec 30 '15 11:12

Michael Seltenreich


People also ask

Is indexing possible in MongoDB?

MongoDB provides a method called createIndex() that allows user to create an index. The key determines the field on the basis of which you want to create an index and 1 (or -1) determines the order in which these indexes will be arranged(ascending or descending).

How do I find the index of a document in MongoDB?

Finding indexes You can find all the available indexes in a MongoDB collection by using the getIndexes method. This will return all the indexes in a specific collection. Result: The output contains the default _id index and the user-created index student name index.

What is compound indexing in MongoDB?

MongoDB supports compound indexes, where a single index structure holds references to multiple fields [1] within a collection's documents. The following diagram illustrates an example of a compound index on two fields: click to enlarge. [1] MongoDB imposes a limit of 32 fields for any compound index.

Can you create an index in an array field in MongoDB?

To index a field that holds an array value, MongoDB creates an index key for each element in the array. These multikey indexes support efficient queries against array fields. Multikey indexes can be constructed over arrays that hold both scalar values [1] (e.g. strings, numbers) and nested documents.


1 Answers

As Blakes Seven mentioned, it is not possible to index across collections.

In cases where this kind of full text search has been paramount to my application, the classic solution is to denormalize the field and included it in both collections. In this case, your Book collection would look like:

Book: {
  title: String,
  description: String
  author: {
    type: mongoose.Schema.Types.ObjectId, 
    ref: 'User',
    ### New field ###
    username: String
  },
}

Now you can index on author.username.

It is entirely dependent on your application whether or not that is a good idea. Downsides include synchronizing username across collections and adding unnecessary weight to each document.

like image 106
tyleha Avatar answered Oct 28 '22 02:10

tyleha