Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find difference between 2 documents on mongoDB from the mongo shell

Tags:

mongodb

I'm using mongodb 2.4.4 and I want to compare 2 documents, then print their differences only using the mongo shell. Is there a way to compare them? Something like:

db.collection.compare({first_doc: objectID("blablalba"), sec_doc: objectID("blalba2")})

and the output would be something like

{diff1:{latitude:{first_doc:10.000, sec_doc:20.000}},diff2:{}}

where latitude is the name of the field that had a difference.

The output doesn't need to be exactly like that, but give the same functionality. Thanks

like image 718
otmezger Avatar asked Jun 24 '13 12:06

otmezger


People also ask

How do I compare two MongoDB databases?

compare collections in two different databases (source and destination, databases may be on the same or on different servers) select the collections to compare. analyze each document and tell if it has been added, removed or updated in source collections. synchronize the changes into destination collections.

What is the mongo command to find all documents that match search criteria?

To find documents that match a set of selection criteria, call find() with the <criteria> parameter. MongoDB provides various query operators to specify the criteria.

How do I search multiple documents in MongoDB?

You can query for multiple documents in a collection with collection. find() . The find() method uses a query document that you provide to match the subset of the documents in the collection that match the query.


1 Answers

Just declare native javascript function that can compare two objects in a way you need, then write a code like this:

obj1 = db.test.findOne({"_id" : ObjectId("5176f80981f1e2878e840888")})
obj2 = db.test.findOne({"_id" : ObjectId("5176f82081f1e2878e840889")})
difference(obj1, obj2)

Some native javascript difference functions can be found here or here

P.S. You can also load some third party js libs from shell like this:

load("D:\difference.js")

Hope this help.

like image 116
Andrew Orsich Avatar answered Oct 16 '22 05:10

Andrew Orsich