mongodb java查询指定字段,如何在Java中从MongoDB检索单个字段

这篇博客介绍了如何在MongoDB Java驱动程序3.0.2版本中检索文档的特定字段,例如价格,并将其赋值给Java变量。通过创建查询并使用投影来提取字段,然后使用`getDouble`方法将价格字段转换为double类型存储到变量中。
摘要由CSDN通过智能技术生成

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.

For example my document is:

{

"username":"testusername"

"item":"Sofa"

"price":150.0

}

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.

Also, I am using mongoDB Java version 3.0.2

Thanks

EDIT: 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.

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

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

解决方案

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

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值