开发者社区> 问答> 正文

mongodb的java开发中使用两个字段相等条件查询问题

也就是类似sql中的where 字段A=字段B这样的条件,我查了下网上有些帖子中写的用$where的方式我查询的时候会出错,类似于:new Document("$where",new Document("字段A", "字段B")),驱动版本是3.0
在网上查到了一些资料用法,根据这些方法写了如下代码:
`String ageStr = "function (){return 字段A==字段B};";
Document cond = new Document("$where",ageStr);
FindIterable iterable=mongodao.find(cond);`
查询的时候并没有报错,但是用iterable.forEach(new Block() 循环的时候报错,请教应该怎么写才对?
另外mongodb的java开发文档哪里有比较详细的,官网上的例子实在太简单了没有更多方法的使用说明

展开
收起
落地花开啦 2016-02-28 17:49:38 5980 0
1 条回答
写回答
取消 提交回答
  • 喜欢技术,喜欢努力的人

    首先在mongo shell 里面是 这样查询的
    `db.ttt.find({})
    { "_id" : ObjectId("566e707540b73d11c02cd058"), "a" : 1, "b" : 1, "c" : 3 }
    db.ttt.find({$where:"this.a == this.b"})
    { "_id" : ObjectId("566e707540b73d11c02cd058"), "a" : 1, "b" : 1, "c" : 3 }`
    转化到 java里面
    Document cond = new Document("$where","this.a == this.b");
    如果用 function的话 其实是写js代码

    function a(){
    if(this.a == this.b)
    return true
    return false
    }

    也就是写成 Document cond = new Document("$where","function a(){if(this.a == this.b){return true}return false}");

    2019-07-17 18:49:53
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
Data as a Service - 数据即服务 -- MongoDB⾼级应⽤模式 立即下载
阿里云MongoDB云服务构建 立即下载
饿了么高级架构师陈东明:MongoDB是如何逐步提高可靠性的 立即下载