ℹ️ 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 Logical OR Operator

MongoDB Query Language

Goal -- WPM

Ready
Exercise Algorithm Area
1function findDocumentsByOrConditions(collection, conditions) {
2// Validate input parameters
3if (!collection || typeof collection !== 'object') {
4throw new Error('Invalid collection provided.');
5}
6if (!Array.isArray(conditions) || conditions.length === 0) {
7throw new Error('Conditions must be a non-empty array.');
8}
9
10// Validate each condition object within the array
11for (const condition of conditions) {
12if (typeof condition !== 'object' || condition === null || Object.keys(condition).length === 0) {
13throw new Error('Each condition must be a non-empty object.');
14}
15// Further validation could be added here to check for valid field names and operators within each condition object.
16// For simplicity, we assume valid condition objects are passed.
17}
18
19// Construct the MongoDB query with the '$or' operator
20// The '$or' operator allows you to specify multiple query criteria, and a document
21// will be returned if it matches ANY of the criteria.
22const query = {
23'$or': conditions
24};
25
26// Execute the query
27// In a real application, this would involve a database driver.
28// For this example, we simulate the query execution.
29console.log('Executing query:', JSON.stringify(query));
30// return collection.find(query).toArray(); // Example of actual DB call
31return []; // Placeholder for simulation
32}
33
34// Helper function to simulate a collection with complex query capabilities
35function simulateOrCollection() {
36return {
37find: function(query) {
38console.log('Simulating find with query:', query);
39return {
40toArray: function() {
41console.log('Simulating toArray call.');
42// Simulate results based on a hypothetical dataset
43const results = [];
44const orConditions = query.$or;
45
46const mockData = [
47{ _id: 1, name: 'Alice', city: 'New York', age: 30, status: 'active' },
48{ _id: 2, name: 'Bob', city: 'Los Angeles', age: 25, status: 'inactive' },
49{ _id: 3, name: 'Charlie', city: 'New York', age: 35, status: 'active' },
50{ _id: 4, name: 'David', city: 'Chicago', age: 28, status: 'active' },
51{ _id: 5, name: 'Eve', city: 'Los Angeles', age: 32, status: 'active' }
52];
53
54mockData.forEach(doc => {
55let matchesAnyCondition = false;
56for (const condition of orConditions) {
57// Simple check for condition matching (e.g., { city: 'New York' } or { age: { $gt: 30 } })
58let conditionMet = true;
59for (const field in condition) {
60const operator = Object.keys(condition[field])[0];
61const value = condition[field][operator];
62
63if (operator) { // If an operator is present (e.g., $gt)
64switch (operator) {
65case '$gt': if (!(doc[field] > value)) conditionMet = false; break;
66case '$eq': if (!(doc[field] == value)) conditionMet = false; break;
67// Add more operators as needed for simulation
68default: conditionMet = false; // Unsupported operator in simulation
69}
70} else { // Direct equality check
71if (doc[field] !== value) {
72conditionMet = false;
73}
74}
75if (!conditionMet) break; // If one field in condition fails, move to next condition
76}
77if (conditionMet) {
78matchesAnyCondition = true;
79break; // If one condition is met, document matches
80}
81}
82if (matchesAnyCondition) {
83results.push(doc);
84}
85});
86return results;
87}
88};
89}
90};
91}
92
93// Example Usage:
94// const peopleCollection = simulateOrCollection();
95// const orQueryConditions = [
96// { city: 'New York' },
97// { status: 'inactive' },
98// { age: { '$gt': 30 } }
99// ];
100// const orResults = findDocumentsByOrConditions(peopleCollection, orQueryConditions);
101// console.log('OR Results:', orResults);
Algorithm description viewbox

MongoDB Find Documents with Logical OR Operator

Algorithm description:

This function demonstrates how to construct MongoDB queries that use the `$or` operator to find documents matching any of a set of specified conditions. This is essential for building flexible search functionalities where a record might satisfy one of several criteria. For instance, it can find customers who are either in a specific city OR have a certain status OR are above a certain age. The function includes validation for the conditions array and its elements.

Algorithm explanation:

The `findDocumentsByOrConditions` function builds a MongoDB query using the `$or` operator. The `$or` operator takes an array of query documents, and a document is returned if it matches at least one of these query documents. Input validation ensures that the `conditions` parameter is a non-empty array of valid query objects. The time complexity of `$or` queries can be complex. If the individual conditions can use indexes, performance can be good. However, if the conditions are broad or cannot leverage indexes effectively, it can approach O(N*M), where N is the number of documents and M is the number of conditions. MongoDB's query optimizer tries to use indexes for each condition. Space complexity is O(1) for query construction. Edge cases include an empty `$or` array (which is handled by validation), conditions that are themselves complex (e.g., nested `$and` or other operators), and scenarios where no conditions are met, resulting in an empty result set.

Pseudocode:

function findDocumentsByOrConditions(collection, conditions):
  validate collection, conditions (must be non-empty array of objects)
  create query object:
    $or: conditions
  execute query on collection
  return results