本文介绍了如何使用Java进行MongoDB查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须使用java编写一个简单的MongoDB查询,但无法执行.

I have to write a simple MongoDB query using java but am not able to do it.

mongo查询如下:

The mongo query looks like this:

db.yourCollection.find({"$where" : "this.startDate < this.endDate"})

我必须使用QueryBuilder类编写以上查询.但是无法在MongoDB java驱动程序中完成此操作.

I have to write the above query using the QueryBuilder class. But am not able to do it in MongoDB java driver.

BasicDBObject document = new BasicDBObject();
document.put("id", 1001);
document.put("intValue", 1200);
document.put("updateValue", 2100);

DBObject query = QueryBuilder.start("intValue").lessThan("updateValue").get();
DBCursor cursor = collection.find(query);
while (cursor.hasNext()) {
System.out.println("Result : -"+cursor.next());}

上面的代码不返回任何结果.但是,如果将updateValue更改为2100,则会得到结果.我的问题是lessThan将对象作为输入参数.那我怎样才能将文档字段作为输入参数呢?

The above code does not return any results. But if changed to updateValue into 2100 it is giving result. My question here is lessThan takes object as input parameter. Then how can I pass document field as an input parameter?

推荐答案

理想情况下,您的mongoDB查询应该是这样的:-

Ideally your mongoDB query should be like this: -

db.yourCollection.find({"startDate": {$lt: endDate}})

可以用Java编写,如下所示:-

which can be written in Java like this: -

BasicDBObject query = new BasicDBObject("startDate", new BasicDBObject("$lt", endDate);
DBCursor cursor = coll.find(query);

您可以查看官方教程

如果您想使用 QueryBuilder ,则可以像这样:-

If you want to use QueryBuilder, you can do it like this: -

DBObject query = QueryBuilder.start("startDate").lessThan("endDate").get();
DBCursor cursor = coll.find(query);

这篇关于如何使用Java进行MongoDB查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 06:51