Mongo的Java驱动程序,如何构建复杂的查询

时间:2014-06-04 13:56:24

标签: java sql mongodb mongodb-query database

我正在测试一个包含一个文档的数据库。使用以下代码,我从数据库中获得以下结果

BasicDBObject keys = new BasicDBObject();
keys.put("symbol", 1 );
keys.put("price", 1 );
keys.put("Exchange", "SH");
keys.put("NumShares", new BasicDBObject("$gte", 0) );

BasicDBObject empty = new BasicDBObject();

DBCursor cursor_02 = coll_tmp.find( empty, keys );
System.out.println( "<2> " + cursor_02.count());
while(cursor_02.hasNext()) {
    System.out.println( "<2>  " + cursor_02.next());
}

这将打印出以下数据

<2>  { <id & oid> , "symbol" : "ESLR" , "Exchange" : "SH"}

该文档还有一个“NumShares”字段,其值设置为2.34508872。想要试用$ gt,$ gte,$ lt,$ lte和$ ne运算符,我会在最后一行'keys.put()'行之后添加一行代码。

keys.put("Price", new BasicDBObject("$gte", 0) );

此代码应继续选择单独的文档,因为它的NumShares字段确实大于或等于零。相反,我得到以下错误。

Can't canonicalize query: BadValue Unsupported projection option: NumShares: { $gte: 0 }

目标最终是使MongoDB等同于SQL查询“SELECT price,symbol,exhange FROM stock WHERE NumShares&gt; = 0,等等......”

我意识到mkyong doesn't cover this particular query structure in his tutorial,所以我问你们所有人。感谢

2 个答案:

答案 0 :(得分:3)

您希望将条件放在查询中,而不是放在要返回的键列表中:

BasicDBObject keys = new BasicDBObject(); // will specify the returned fields (SELECT)
keys.put("symbol", 1 );
keys.put("price", 1 );
keys.put("Exchange", 1);

BasicDBObject query = new BasicDBObject(); // will select the documents you want (WHERE)
query.put("numShares", new BasicDBObject("$gte", 0) ); 

DBCursor cursor_02 = coll_tmp.find( query, keys );
System.out.println( "<2> " + cursor_02.count());
while(cursor_02.hasNext()) {
    System.out.println( "<2>  " + cursor_02.next());
}

答案 1 :(得分:2)

您需要将结果限制查询参数放到查询的第一个Object中。第二个对象是结果的投影。它只能指定要显示的标签(如true / 1或false / 0),没有其他限制,例如“$ lte”允许。将它放在查询对象中,如下所示:

BasicDBObject keys = new BasicDBObject();
keys.put("symbol", 1 );
keys.put("price", 1 );
keys.put("Exchange", 1);

BasicDBObject search = new BasicDBObject();
search.put("Exchange", "SH");
search.put("numShares", new BasicDBObject("$gte", 0) );

DBCursor cursor_02 = coll_tmp.find(search, keys);

MongoDBs文档密钥也区分大小写。因此,如果您的密钥是“NumShares”,则无法通过查找“numShares”找到它。