gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 21:50:46 25 4
gpt4 key购买 nike

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

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 >= 0, etc...”

我意识到 mkyong doesn't cover this particular query structure in his tutorial ,所以我问大家。谢谢

最佳答案

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

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());
}

关于java - Mongo 的 Java 驱动程序,如何构建复杂的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24039423/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com