获取MongoDB Java中数组子文档字段的值。

huangapple go评论92阅读模式
英文:

Retrieve only the value of an arrays sub-document field using MongoDB Java

问题

我有一个数据库:

{
"_id": {
"$oid": "1"
},
"lastName": {
"lastName": "James"
},
"data": [{
"day": "20-09-2020 11:35:02",
"hoursWorked": "0小时:5分钟:321秒"
}, {
"day": "20-09-2020 11:35:29",
"hoursWorked": "0小时:5分钟:321秒"
}]
}

如何仅检索“data”字段的子字段“hoursWorked”的值。
因此,我只需要该字段的值或所有这些值,即0小时:5分钟:321秒。

我使用以下代码;然而,我仍然无法检索到该值。

  1. Document document = collection
  2. .find(new BasicDBObject("_id", y))
  3. .projection(Projections.fields(Projections.include("data.hoursWorked"), excludeId())).first();
  4. System.out.println(document);
  5. }
英文:

I have a database:

  1. {
  2. "_id": {
  3. "$oid": "1"
  4. },
  5. "lastName": {
  6. "lastName": "James"
  7. },
  8. "data": [{
  9. "day": "20-09-2020 11:35:02",
  10. "hoursWorked": "0 hours : 5 mins : 321 secs"
  11. }, {
  12. "day": "20-09-2020 11:35:29",
  13. "hoursWorked": "0 hours : 5 mins : 321 secs"
  14. }]
  15. }

How do I retrieve only the value of subfield "hoursWorked" of "data" field.
So, I need only the value or all values of such field, 0 hours : 5 mins : 321 secs.

I use the following; however, I still cannot retrieve the value.

  1. Document document = collection
  2. .find(new BasicDBObject("_id", y))
  3. .projection(Projections.fields(Projections.include("data.hoursWorked"), excludeId())).first();
  4. System.out.println(document);
  5. }

答案1

得分: 1

  1. 使用 MongoDB Java 驱动程序
  2. List<Bson> pipeline =
  3. Arrays.asList(
  4. project(
  5. fields(
  6. excludeId(),
  7. computed("hoursWorked",
  8. eq("$reduce",
  9. and(eq("input", "$data"), eq("initialValue", Arrays.asList()),
  10. eq("in", eq("$concatArrays", Arrays.asList("$$value", Arrays.asList("$$this.hoursWorked"))))
  11. )
  12. )
  13. )
  14. )
  15. ),
  16. unwind("$hoursWorked")
  17. );
  18. collection.aggregate(pipeline)
  19. .into(new ArrayList<Document>())
  20. .forEach(doc -> System.out.println(doc.get("hoursWorked")));
  21. 打印data数组中的两个值
  22. 0小时5分钟321
  23. 0小时5分钟322
英文:

Using MongoDB Java Driver:

  1. List&lt;Bson&gt; pipeline =
  2. Arrays.asList(
  3. project(
  4. fields(
  5. excludeId(),
  6. computed(&quot;hoursWorked&quot;,
  7. eq(&quot;$reduce&quot;,
  8. and(eq(&quot;input&quot;, &quot;$data&quot;), eq(&quot;initialValue&quot;, Arrays.asList()),
  9. eq(&quot;in&quot;, eq(&quot;$concatArrays&quot;, Arrays.asList(&quot;$$value&quot;, Arrays.asList(&quot;$$this.hoursWorked&quot;) ) ) )
  10. )
  11. )
  12. )
  13. )
  14. ),
  15. unwind(&quot;$hoursWorked&quot;)
  16. );
  17. collection.aggregate(pipeline)
  18. .into(new ArrayList&lt;Document&gt;())
  19. .forEach(doc -&gt; System.out.println(doc.get(&quot;hoursWorked&quot;)));

Prints two values from the data array:

  1. 0 hours : 5 mins : 321 secs
  2. 0 hours : 5 mins : 322 secs

答案2

得分: 0

你可以使用投影 $project

  1. db.collection.aggregate([
  2. {
  3. $project: {
  4. "data.hoursWorked": 1
  5. }
  6. }
  7. ])

Mongo 游乐场 中运行

在 Spring Boot 中,你需要自动装配 mongoTemplate

  1. @Autowired
  2. MongoTemplate mongoTemplate;

聚合代码:

  1. public List<Object> test(){
  2. Aggregation aggregation = Aggregation.newAggregation(
  3. a-> new Document("$project",
  4. new Document("data.hoursWorked", 1)
  5. )
  6. ).withOptions(AggregationOptions.builder().allowDiskUse(Boolean.TRUE).build());
  7. return mongoTemplate.aggregate(aggregation, mongoTemplate.getCollectionName(YOUR_COLLECTION.class), Object.class).getMappedResults();
  8. }

更新 1

使用 Bson.Document

  1. Document nodes = (Document) collection
  2. .find(new BasicDBObject("_id", "1"))
  3. .projection(Projections.fields(Projections.include("data.hoursWorked"), Projections.excludeId()))
  4. .first();
  5. List<Document> list = (List<Document>) nodes.get("data");
  6. for(Document d:list){
  7. System.out.println(d.get("hoursWorked"));
  8. }
英文:

You can use projection $project.

  1. db.collection.aggregate([
  2. {
  3. $project: {
  4. &quot;data.hoursWorked&quot;: 1
  5. }
  6. }
  7. ])

Working Mongo playground

In spring boot, you need to autowire the mongoTemplate

  1. @Autowired
  2. MongoTemplate mongoTemplate;

The aggregation code,

  1. public List&lt;Object&gt; test(){
  2. Aggregation aggregation = Aggregation.newAggregation(
  3. a-&gt; new Document(&quot;$project&quot;,
  4. new Document(&quot;data.hoursWorked&quot;,1)
  5. )
  6. ).withOptions(AggregationOptions.builder().allowDiskUse(Boolean.TRUE).build());
  7. return mongoTemplate.aggregate(aggregation, mongoTemplate.getCollectionName(YOUR_COLLECTION.class), Object.class).getMappedResults();
  8. }

Update 1

Using Bson.Doument

  1. Document nodes = (Document) collection
  2. .find(new BasicDBObject(&quot;_id&quot;, &quot;1&quot;))
  3. .projection(Projections.fields(Projections.include(&quot;data.hoursWorked&quot;), Projections.excludeId()))
  4. .first();
  5. List&lt;Document&gt; list = (List&lt;Document&gt;) nodes.get(&quot;data&quot;);
  6. for(Document d:list){
  7. System.out.println(d.get(&quot;hoursWorked&quot;));
  8. }

huangapple
  • 本文由 发表于 2020年9月21日 07:41:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/63984636.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定