MongoDB: How to compare 2 documents (with examples)

Updated: February 4, 2024 By: Guest Contributor Post a comment

Introduction

MongoDB, a popular NoSQL database, supports flexible document structures, making it a pivotal choice for a broad range of applications. Nonetheless, comparing two documents can sometimes pose a challenge given this flexibility. Learning how to effectively compare documents can assist in various tasks such as data validation, duplicate identification, and document version control.

Comparing two documents in MongoDB can range from straightforward comparisons using queries and operators to more complex situations necessitating the use of aggregation pipelines or external libraries. This guide illustrates various techniques to achieve this, from basic to advanced, complemented with examples and expected outputs.

Basic Comparison Using JSON.stringify

The simplest way to compare two documents in MongoDB is by converting them into strings using JSON.stringify and then comparing the strings:

const doc1 = {name: 'Alice', age: 30};
const doc2 = {name: 'Alice', age: 30};

if (JSON.stringify(doc1) === JSON.stringify(doc2)) {
  console.log ('Documents are identical.');
} else {
  console.log ('Documents differ.');
}

Note: This method is highly sensitive to property order and does not handle complex objects or objects with functions.

Intermediate Comparison Using Operators

In certain situations, comparing specific fields rather than entire documents is preferable. MongoDB’s query operators can be utilized here:

db.collection.find({
  $expr: {
    $and: [
      { $eq: ["$field1", TARGET_VALUE] },
      { $eq: ["$field2", TARGET_VALUE] }
    ]
  }
});

This method allows for the comparison of specific fields across documents in a collection but requires both documents to exist within the MongoDB collection.

Advanced Comparison Using Aggregation

For more complex comparisons, MongoDB’s aggregation framework offers a more flexible set of tools. The following example demonstrates how to compare two documents by computing a similarity score based on the number of matching fields:

db.collection.aggregate([
  {
    $project: {
      similarityScore: {
        $size: {
          $filter: {
            input: {
              $objectToArray: "$document"
            },
            as: "element",
            cond: {
              $eq: ["$element.v", TARGET_VALUE]
            }
          }
        }
      }
    }
  }
]);

This query transforms each document into an array of its fields, then filters those fields based on a target value, and finally calculates the similarity score based on the number of fields that match the target value. Such comparisons are beneficial in identifying similar documents or determining document versions.

Comparing Documents Using External Libraries

There are instances where MongoDB’s built-in features may not suffice for document comparison. External JavaScript libraries like Lodash or Underscore can offer additional flexibility:

const _ = require('lodash');

const isEqual = _.isEqual(doc1, doc2);
if (isEqual) {
  console.log('Documents are identical.');
} else {
  console.log('Documents differ.');
}

This method is particularly useful for deep comparisons and when handling documents with nested objects or arrays.

Conclusion

Comparing documents in MongoDB can be approached in various ways, depending on the complexity of the documents and the specifics of the comparison required. Starting from simple JSON extraction and string comparison to leveraging MongoDB operators or even employing external libraries for deep comparisons, developers have multiple tools at their disposal to identify similarities or differences between documents. Understanding these methods and their applications can significantly enhance one’s ability to work with MongoDB data efficiently.