我试图“比较”2个集合之间的所有文档,这将仅返回true,如果只有2个集合中的所有文档完全相同。
我一直在搜索关于集合的方法,但找不到可以做到这一点的方法。
我在mongo shell中尝试过类似的东西,但没有像我预期的那样工作:
db.test1 == db.test2
或
db.test1.to_json() == db.test2.to_json()
无论如何,我还在java中使用spring-data mongodb。
请分享您的想法!谢谢。
答案 0 :(得分:13)
您可以尝试将mongodb eval与自定义等号功能结合使用,例如this。
您的方法不起作用,因为在第一种情况下,您正在比较不同的对象引用。在第二种情况下,即使对于相同的对象,也无法保证to_json将生成相同的字符串。
相反,尝试这样的事情:
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,您可以确保在数据库服务器端执行代码,而无需将集合提取到客户端。