Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare 2 mongodb collections?

Tags:

mongodb

Im trying to 'compare' all documents between 2 collections, which will return true only and if only all documents inside 2 collections are exactly equal.

I've been searching for the methods on the collection, but couldnt find one that can do this.

I experimented something like these in the mongo shell, but not working as i expected :

db.test1 == db.test2

or

db.test1.to_json() == db.test2.to_json()

Please share your thoughts ! Thank you.

like image 516
Albert Gan Avatar asked Feb 11 '12 13:02

Albert Gan


People also ask

Does MongoDB support relationship between collections?

MongoDB (and most other NoSQL databases) do not natively support the concept of relations.

What is comparison operator in MongoDB?

It is used to match the values of the fields that are equal to a specified value. It is used to match all values of the field that are not equal to a specified value. It is used to match values of the fields that are greater than a specified value.

Can we have multiple collections in MongoDB?

As mentioned above, a single database can have multiple collections.


1 Answers

You can try using mongodb eval combined with your custom equals function, something like this.

Your methods don't work because in the first case you are comparing object references, which are not the same. In the second case, there is no guarantee that to_json will generate the same string even for the objects that are the same.

Instead, try something like this:

var compareCollections = function(){
    db.test1.find().forEach(function(obj1){
        db.test2.find({/*if you know some properties, you can put them here...if don't, leave this empty*/}).forEach(function(obj2){
            var equals = function(o1, o2){
                // here goes some compare code...modified from the SO link you have in the answer.
            };

            if(equals(ob1, obj2)){
                // Do what you want to do
            }
        });
    });
};

db.eval(compareCollections);

With db.eval you ensure that code will be executed on the database server side, without fetching collections to the client.

like image 182
Aleksandar Vucetic Avatar answered Sep 17 '22 18:09

Aleksandar Vucetic