ℹ️ 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 Existence Check

MongoDB Query Language

Goal -- WPM

Ready
Exercise Algorithm Area
1function findDocumentsByFieldExistence(collection, fieldName, shouldExist) {
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 shouldExist !== 'boolean') {
10throw new Error('shouldExist must be a boolean.');
11}
12
13// Construct the MongoDB query for field existence
14// The '$exists' operator checks if a field is present or absent in a document.
15// It takes a boolean value: true to check for existence, false for absence.
16const query = {
17[fieldName]: {
18'$exists': shouldExist
19}
20};
21
22// Execute the query
23// In a real application, this would involve a database driver.
24// For this example, we simulate the query execution.
25console.log('Executing query:', JSON.stringify(query));
26// return collection.find(query).toArray(); // Example of actual DB call
27return []; // Placeholder for simulation
28}
29
30// Helper function to simulate a collection
31function simulateExistenceCollection() {
32return {
33find: function(query) {
34console.log('Simulating find with query:', query);
35return {
36toArray: function() {
37console.log('Simulating toArray call.');
38// Simulate results based on a hypothetical dataset
39const results = [];
40const field = Object.keys(query)[0];
41const exists = query[field].$exists;
42
43const mockData = [
44{ _id: 1, name: 'User A', email: 'a@example.com', age: 30 },
45{ _id: 2, name: 'User B', email: 'b@example.com', age: null },
46{ _id: 3, name: 'User C', email: null, age: 25 },
47{ _id: 4, name: 'User D', age: 40 },
48{ _id: 5, name: 'User E', email: 'e@example.com' }
49];
50
51mockData.forEach(doc => {
52const hasField = doc.hasOwnProperty(field);
53if (exists && hasField) {
54// If we expect it to exist, and it does, add it.
55// Note: $exists: true matches fields present, even if null.
56results.push(doc);
57} else if (!exists && !hasField) {
58// If we expect it to not exist, and it doesn't, add it.
59results.push(doc);
60}
61});
62return results;
63}
64};
65}
66};
67}
68
69// Example Usage:
70// const usersCollection = simulateExistenceCollection();
71// const existenceResults = findDocumentsByFieldExistence(usersCollection, 'age', false);
72// console.log('Existence Results:', existenceResults);
Algorithm description viewbox

MongoDB Find Documents with Existence Check

Algorithm description:

This function demonstrates how to query MongoDB documents based on whether a specific field exists or is absent. It uses the `$exists` operator, which is crucial for data validation and ensuring data integrity. For example, it can find all users who have not provided an email address or all products that have a 'discountPrice' field set. The function includes validation for the field name and the boolean flag indicating existence.

Algorithm explanation:

The `findDocumentsByFieldExistence` function constructs a MongoDB query using the `$exists` operator. This operator takes a boolean value: `true` to find documents where the field is present (even if its value is `null`), and `false` to find documents where the field is absent. Input validation ensures the `fieldName` is a string and `shouldExist` is a boolean. The `$exists` operator can be efficient if the field is indexed, potentially offering O(log N) performance. Without an index, it defaults to O(N). Space complexity is O(1) for query construction. Edge cases include fields explicitly set to `null` (which `$exists: true` will match) and fields that are completely missing from a document (which `$exists: false` will match). It's important to distinguish between a field being `null` and a field being absent.

Pseudocode:

function findDocumentsByFieldExistence(collection, fieldName, shouldExist):
  validate collection, fieldName, shouldExist
  create query object:
    field[fieldName] exists (if shouldExist is true)
    OR field[fieldName] does not exist (if shouldExist is false)
  execute query on collection
  return results