How to compare 2 mongodb collections?

后端 未结 1 1651
暗喜
暗喜 2020-12-05 16:37

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

相关标签:
1条回答
  • 2020-12-05 16:46

    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.

    0 讨论(0)
提交回复
热议问题