如何在Java中从MongoDB检索单个字段 [英] How to retrieve a single field from MongoDB in Java

查看:875
本文介绍了如何在Java中从MongoDB检索单个字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从文档中检索一个字段并将其设置为等于变量,因此稍后更新时,我可以执行(field + newCount)之类的操作.

I am trying to retrieve a field from a document and set it equal to a variable so when I update it later I can just do (field + newCount) or something like that.

例如,我的文档是:

{
"username":"testusername"
"item":"Sofa"
"price":150.0
}

如何检索价格字段并将其设置为等于double currentPrice;?

How do I retrieve the price field and set it equal to let's say double currentPrice; ?

文档有点含糊,因此举个例子会有所帮助.

The documentation is a bit ambiguous so an example would help.

此外,我正在使用mongoDB Java版本3.0.2

Also, I am using mongoDB Java version 3.0.2

谢谢

显然,这个问题有点模棱两可,但是我试图检索存储在数据库中的沙发的价格,并将其设置为与我的Java代码中的变量相等.

Apparently the question is a bit ambiguous, but I am trying to retrieve the price of the sofa that is stored in the database, and set it equal to a variable in my java code.

因此,我想将其设置为double currentPrice = 150.0;

So, I would like to set it so that double currentPrice = 150.0;

那么我该如何使用Java代码访问商品价格并将其设置为变量?

So how can I use java code to access the price of the item and set it to a variable?

推荐答案

以下是如何从驱动程序版本3.0.2的MongoDB中检索单个字段的方法:创建带有投影的查询:

Here is how you'd retrieve a single field from MongoDB, driver version 3.0.2 You create a query with a projection:

    Document document = collection
            .find(new BasicDBObject("username", "testusername"))
             .projection(Projections.fields(Projections.include("price"), Projections.excludeId())).first();

然后,您可以使用以下代码将此字段提取为double:

Then, you can extract this field as double with the following code:

    double price = document.getDouble("price");

这篇关于如何在Java中从MongoDB检索单个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆