Max Mikhalchuk
Max Mikhalchuk

Reputation: 147

MongoDB: Making a series of queries

Situation

After some manipulations, I get a string like this: qwertyuiop. And using MongoDB I need to search every substring of that string. So I need to make many queries: qwertyuiop, qwertyuio, qwertyui, qwertyu ... qw, q (after each query, I subtract 1 letter from the right, till that string become a letter). So my node.js code iterates an array of substrings and makes each time MongoDB query.

Problem

This code is heavy for the database and that's the reason of the low performance. I don't know MongoDB and node.js well. I'll be happy if you help me with this situation.

Upvotes: 0

Views: 70

Answers (1)

tfogo
tfogo

Reputation: 1436

You you could use the $in operator to search for all of these matches in a single query:

db.collection.find({ fieldName: { $in: ['qwertyuiop', 'qwertyuio', 'qwertyui', 'qwertyu', 'qwerty', 'qwert','qwer', 'qwe', 'qw', 'q'] } })

Alternatively, you could search using a regex:

db.collection.find({ fieldName: /^qw?e?r?t?y?u?i?o?p?/ })

If you're unfamiliar with regex, here's a tutorial.

Although this will allow you to only make one query to the database, these queries can be quite expensive by themselves. It's important that you index the field on which you are matching so that you have the best performance.

If you use regex, there are extra considerations to make sure they are efficient. For example, be sure you don't use case insensitive regexes so that you can make best use of your indexes.

Upvotes: 1

Related Questions