Search code examples
mongodbgoogle-cloud-firestoredatabase-designnosql

What is the best way to structure the database for tag-based fetching in a cloud database?


I am confused about the way I need to structure my documents to effectively search/fetch items by tag when needed.

Meaning, the structure of each document goes like:

{
  name: "Delicious blackforest cake",
  tags: ["blackforest","birthday","designer"]
  ...
}
{
  name: "Red velvet cake",
  tags: ["party","anniversary","designer"]
  ...
}
...

There's a total of 32 tags, and I want to fetch the cakes based on tags. This is my present structure which I feel would be inefficient while fetching.

And I want to search based on tags and name of the cake, for example

If I search de, the search suggestions should be:

  • designer cake /* This is based on a tag */
  • Delicious blackForest cake /* This is based on an actual name */

As per my knowledge, I guess this is difficult to achieve in Firebase. Should I opt for MongoDB or should I change the structure of the document?

I want a suggestion to effectively search and fetch according to my above-stated needs.


Solution

  • Firestore can be used for this use case. The array-contains operator can be used to query documents where tags array contains a specific value.

    await colRef.where("tags", "array-contains", "tag")
    

    If your use case required to find documents with multiple tags, then you might have to use a map instead of array. Checkout Firestore search array contains for multiple values.

    MongoDB has a $all operator that can be used for this as shown below:

    await collection.find({ tags: { $all: ["tag"] } })
    

    For full-text search, you'll have to use a search service as also mentioned in the documentation for best results. Although MongoDB has a $search operator (uses Apache Lucene as far as I know), it can be used only when you host your database on Atlas otherwise you'll have to rely on $text operator. Firestore Algolia Extension should do most of the work for you and let you use all full text search capabilities of Algolia.

    Additionally, if you use Algolia with Firestore, you can get even better support for filtering by tags so you won't have to use a map instead of array as mentioned earlier.