Find the difference between two documents on mongoDB from mongo shell

I am using mongodb 2.4.4 and I want to compare 2 documents and then print their differences only using mongo shell. Is there any way to compare them? Sort of:

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

and the output will be something like

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

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

The output does not have to be the same, but gives the same functionality. Thanks

+6
source share
1 answer

Just declare your own javascript function, which can compare two objects as you need, and then write code like this:

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

Some built-in javascript markup functions can be found here or here.

PS You can also download some third-party js libs from the shell as follows:

 load("D:\difference.js") 

I hope for this help.

+4
source

Source: https://habr.com/ru/post/947992/


All Articles