【问题标题】:How to return only 1 field in MongoDB?如何在 MongoDB 中只返回 1 个字段?
【发布时间】:2020-05-06 15:43:22
【问题描述】:

我正在尝试获取 transactionId 等于我在代码中的另一个变量的订单号。我的 tolls.booths 集合看起来像这样

在我的代码中, def boothsException = booths.find([ "pings.loc.transactionId": tollEvent.id, "pings.loc.order":1] as BasicDBObject).iterator() println boothsException

我收到boothsException = DBCursor{collection=DBCollection{database=DB{name='tolls'} 我基本上想说 get where transactionId = 410527376 并在boothsException (5233423) 中给我那个订单号。

【问题讨论】:

    标签: java mongodb groovy mongodb-query mongodb-java


    【解决方案1】:

    这是使用MongoDB Java Driver v3.12.2

    代码从返回的游标中提取值。我使用的是较新的 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
    }
    


    注意事项:

    带有投影的查询从pings 数组中获取以下一个子文档:

    "pings" : [
                    {
                        "upvote" : 575,
                        "loc" : {
                                "type" : "2dsphere",
                                "coordinates" : [ .... ],
                                "transactionId" : 410527376,
                                "order" : 5233423
                        },
                        ...
                }
    ]
    

    循环游标的剩余代码是从中提取order 值。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多