如何使用 Java 驱动程序为 MongoDB 构建 $or 查询?

编程入门 行业动态 更新时间:2024-10-27 14:25:03
本文介绍了如何使用 Java 驱动程序为 MongoDB 构建 $or 查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试或 MongoDB 中的某些条件(使用 Java 驱动程序).这就是我正在做的:

I'm trying to Or some conditions in MongoDB (using the Java driver). This is what I'm doing :

Pattern regex = Patternpile("title"); DBCollection coll = MongoDBUtil.getDB().getCollection("post_details"); BasicDBObject query = new BasicDBObject(); query.put("category_title", "myCategory"); query.append("post_title", regex); query.append("post_description", regex); DBCursor cur = coll.find(query); while(cur.hasNext()) { System.out.println(cur.next().get("post_id")); }

我想在这些条件下使用 $or 操作数,但我猜默认是and",我不知道如何更改它.在上面的代码中,如果其中一个条件返回null,结果也会是null.

I'd like to use the $or operand on these conditions, but I guess the default is "and" and I don't know how to change it. In the above code if one of the conditions returns null, the result will be null too.

推荐答案

您是正确的,在查询中指定多个字段的默认"是每个字段都用作条件过滤器,因此是 AND 运算.

You are correct that the "default" for specifying multiple field in a query is that each field serves as a conditional filter, and thus is an AND operation.

您可以使用具有以下语法的 $or 操作数使用 OR 子句执行 MongoDB 查询:

You can perform MongoDB queries with an OR clause by using the $or operand which has the following syntax :

db.col.find({$or:[clause1, clause2]})

其中每个子句都可以是一个查询.$or 不必是顶级操作数,但如果是,MongoDB 可以为每个单独的子句使用索引.

Where each clause can be a query. $or does not have to be a top level operand but if it is MongoDB can use an index for each seperate clause.

在您的示例中,您希望以这个查询结束:

In your example you want to end up with this query :

db.col.find({$or:[{"post_title", regex}, {"post_description", regex}]});

可以通过以下方式在 Java 中构建:

Which can be constructed in Java through :

DBObject clause1 = new BasicDBObject("post_title", regex); DBObject clause2 = new BasicDBObject("post_description", regex); BasicDBList or = new BasicDBList(); or.add(clause1); or.add(clause2); DBObject query = new BasicDBObject("$or", or);

更多推荐

如何使用 Java 驱动程序为 MongoDB 构建 $or 查询?

本文发布于:2023-11-22 12:55:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1617493.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   驱动程序   Java   MongoDB

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!