ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

MongoDB Find Documents with Regex Match

MongoDB Query Language

Goal -- WPM

Ready
Exercise Algorithm Area
1function findDocumentsByRegex(collection, fieldName, pattern, options = {}) {
2// Validate input parameters
3if (!collection || typeof collection !== 'object') {
4throw new Error('Invalid collection provided.');
5}
6if (typeof fieldName !== 'string' || fieldName.length === 0) {
7throw new Error('Invalid fieldName provided.');
8}
9if (typeof pattern !== 'string' || pattern.length === 0) {
10throw new Error('Invalid pattern provided.');
11}
12
13// Construct the MongoDB query with regex
14// The '$regex' operator allows for pattern matching within string fields.
15// Options like 'i' for case-insensitivity can be passed.
16const query = {
17[fieldName]: {
18'$regex': pattern,
19'$options': options.caseInsensitive ? 'i' : ''
20}
21};
22
23// Execute the query
24// In a real application, this would involve a database driver.
25// For this example, we simulate the query execution.
26console.log('Executing query:', JSON.stringify(query));
27// return collection.find(query).toArray(); // Example of actual DB call
28return []; // Placeholder for simulation
29}
30
31// Helper function to simulate a collection
32function simulateRegexCollection() {
33return {
34find: function(query) {
35console.log('Simulating find with query:', query);
36return {
37toArray: function() {
38console.log('Simulating toArray call.');
39// Simulate results based on a hypothetical dataset
40const results = [];
41const regex = new RegExp(query[Object.keys(query)[0]].$regex, query[Object.keys(query)[0]].$options);
42const field = Object.keys(query)[0];
43
44const mockData = [
45{ _id: 1, name: 'Apple Inc.', industry: 'Technology' },
46{ _id: 2, name: 'Apple Pie Recipes', industry: 'Food' },
47{ _id: 3, name: 'Microsoft Corporation', industry: 'Technology' },
48{ _id: 4, name: 'Pineapple Juice', industry: 'Beverage' }
49];
50
51mockData.forEach(doc => {
52if (regex.test(doc[field])) {
53results.push(doc);
54}
55});
56return results;
57}
58};
59}
60};
61}
62
63// Example Usage:
64// const companiesCollection = simulateRegexCollection();
65// const regexResults = findDocumentsByRegex(companiesCollection, 'name', '^App', { caseInsensitive: true });
66// console.log('Regex Results:', regexResults);
Algorithm description viewbox

MongoDB Find Documents with Regex Match

Algorithm description:

This function demonstrates how to use MongoDB's `$regex` operator to perform pattern matching on string fields. It allows for flexible searching based on regular expression patterns, making it ideal for finding data that adheres to specific formats or contains certain substrings. The function supports case-insensitive matching and includes validation for input parameters. A common use case is searching for user inputs like email addresses or product names that follow a particular structure.

Algorithm explanation:

The `findDocumentsByRegex` function constructs a MongoDB query that utilizes the `$regex` operator to match string fields against a given pattern. The `options` parameter allows for modifiers like case-insensitivity ('i'). Input validation checks for valid collection, field name, and pattern. The time complexity of a `$regex` query depends heavily on the pattern and whether the field is indexed. If the field is indexed and the regex is anchored to the beginning of the string (e.g., `/^abc/`), performance can be good. However, if the regex is not anchored or is complex, it can degrade to O(N), where N is the number of documents, as it may require a full collection scan. Space complexity is O(1) for query construction. Edge cases include empty patterns, patterns that match too broadly, and fields that are not strings, which would result in no matches or errors if not handled by MongoDB's type coercion.

Pseudocode:

function findDocumentsByRegex(collection, fieldName, pattern, options):
  validate collection, fieldName, pattern
  create query object:
    field[fieldName] matches pattern
    apply options (e.g., case-insensitive)
  execute query on collection
  return results