Java 如何在MongoDB中只返回1个字段?

Java 如何在MongoDB中只返回1个字段?,java,mongodb,groovy,mongodb-query,mongodb-java,Java,Mongodb,Groovy,Mongodb Query,Mongodb Java,我试图获取订单号,其中transactionId等于代码中的另一个变量。我的收费亭收藏是这样的 在我的代码中, def boothexception=booths.find([“pings.loc.transactionId”:tollEvent.id,“pings.loc.order”:1]作为基本CDBObject)。迭代器() println引导异常 我得到了boothexception=DBCursor{collection=DBCollection{database=DB{name=

我试图获取订单号,其中transactionId等于代码中的另一个变量。我的收费亭收藏是这样的

在我的代码中,
def boothexception=booths.find([“pings.loc.transactionId”:tollEvent.id,“pings.loc.order”:1]作为基本CDBObject)。迭代器()
println引导异常

我得到了
boothexception=DBCursor{collection=DBCollection{database=DB{name='tolls'}
基本上,我想说的是获取where transactionId=410527376,并在BoothException(5233423)中给我那个订单号

代码从返回的游标中提取值。我正在使用较新的API,因此您会发现类名中存在一些差异

int transId = 410527376;    // same as tollEvent.id

MongoCursor<Document> cursor = collection
                                   .find(eq("pings.loc.transactionId", transId))
                                   .projection(fields(elemMatch("pings.loc.transactionId"), excludeId()))
                                   .iterator();
while (cursor.hasNext()) {
    Document doc = cursor.next();
    List<Document> pings = doc.get("pings", List.class);
    Integer order = pings.get(0).getEmbedded(Arrays.asList("loc","order"), Double.class).intValue();
    System.out.println(order.toString());    // prints 5233423
}
循环光标的剩余代码是从中提取
order

以下是与
find
方法的过滤器和投影一起使用的导入:

import static com.mongodb.client.model.Filters.*;
import static com.mongodb.client.model.Projections.*;
import static com.mongodb.client.model.Filters.*;
import static com.mongodb.client.model.Projections.*;