How to compare two documents

How do I compare the equality of two documents? Let’s say I have new data coming from a web form. In that form I have an external id that gets stored along with all the fields. So when data comes from the client, I do a query utilizing that external id, given that I have a match I would like to know if the rest of the values are equals or not, in other words, I’m comparing the entire document against each other, the one coming from the client and the one already in the database.

I would like to know if Mongo itself has an operator ($eq, $lookup, etc) for comparing two documents.

I would like to know if Mongo itself has an operator ($eq, $lookup, etc) for comparing two documents.

@redeemefy we don’t have a basic solution however the blog post “Comparing Subdocuments In MongoDB Expressions” offers a solution that may be suitable for your use case.

Assuming JavaScript you could use JSON.stringify() to compare 2 objects.

a = { "first" : "steeve" , "last" : "juneau" , "id" : "steevej" }
b = { "first" : "steeve" , "last" : "juneau" , "id" : "steevej" }
c = { "first" : "steeve" , "last" : "juneau" , "id" : "steeve" }
JSON.stringify(a) == JSON.stringify(b)
// will be true
JSON.stringify(a) == JSON.stringify(c)
// will be false

With Java, you could use toJson() and do the same comparison.

In python you may compare the dictionary directly.

I believe this approach is not going to work.

const a = { a: 'test', b: 'sample' }
const b = { b: 'sample', a: 'test' }
JSON.stringify(a) == JSON.stringify(b) // false

Same properties and all properties with the same values but those properties in different order in the document returns false.

You are absolutely right. But I have assume that the data always come in the same order as it comes from the same client code.

If you cannot ensure you received the fields in the same order you may sort before stringify and compare:

a = { c: 1, b: 2 }
b = { b: 2, c: 1 }
sorted_a = Object.entries( a ).sort()
sorted_b = Object.entries( b ).sort()

JSON.stringify(a) == JSON.stringify(b) // false

// but

JSON.stringify(sorted_a) == JSON.stringify(sorted_b) // true