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
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).
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With