TLDR: Periodically run a script and set a helper field on each document, adding text from multiple fields and make that field searchable.
Ok, it's not really a hack, just an easy method to circumvent the restriction MongoDB has that only lets you have a single field set to $text
per collection.
Because MongoDB is a business that want to make money, they make some functionality available only via a paid premium license. This is totally fine, and most of the time you will manage great with all the wonderful, free utilities.
However, for my hobby project I wanted to free text search multiple fields in a single document and this isn't allowed in the free license. Instead of implementing Elastic Search, I managed to make it work with only MongoDB
In my project, a user would have basic information on his profile and I wanted to make their email searchable with a free text search. The user also has additional contact information such as city, street address and country, which I also wanted to make searchable via free text search. And finally, they would have a membership which included notes
that I also wanted to make searchable.
My first approach, which I later abandoned was to make three collections: profiles
, memberships
and contactInfo
. This allowed me to index one field per collection as a $text
-field, making it searchable via a free text search. The problem with this approach is that my queries got very complex and super slow because I needed 3 queries each time I wanted a user's profile
, membership
and contactInformation
. And I almost always want those together.
My second approach is a bit hacky, but works great! And it's totally within the bounds of what's allowed with a free license.
Firstly, I restructured my data model to a more NoSQL-ish pattern, where all the information needed together are in a single collection. I simply have a users
collection with profile
, contactInfo
and membership
information on it. With that, I get fast queries and a simple data model. The way I solved my need to free text search on multiple fields is quite easy; periodically run a script that calculates and writes a helper field called keywords
which I build from other relevant fields on the document. I include notes, address, name, city, and any other fields I want and I have it indexed and set to $text
.
This allows me to effectively search multiple fields in a single collection using MongoDB.
Top comments (0)