如何比较2个mongodb集合? [英] How to compare 2 mongodb collections?

查看:101
本文介绍了如何比较2个mongodb集合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试比较"两个集合之间的所有文档,并且仅当两个集合中的所有文档完全相等时才返回true.

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.

我在mongo shell中进行了类似的实验,但未达到我的预期:

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

db.test1 == db.test2

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

无论如何,即时通讯还在Java中使用spring-data mongodb.

Anyway, im also using spring-data mongodb in java.

请分享您的想法!谢谢.

Please share your thoughts ! Thank you.

推荐答案

您可以尝试使用mongodb 评估与自定义的equals函数结合使用,类似于.

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

您的方法不起作用,因为在第一种情况下,您正在比较对象引用,对象引用不同.在第二种情况下,即使对于相同的对象,也无法保证to_json会生成相同的字符串.

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);

使用db.eval,您可以确保代码将在数据库服务器端执行,而无需将集合获取到客户端.

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

这篇关于如何比较2个mongodb集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆