簡體   English   中英

使用 mongodb java 客戶端從數組中獲取第一個元素

[英]Get the first element from an array with mongodb java client

我有一個 JavaScript 代碼。

db.xxx.aggregate([
    {$project: {object:{$first:'$object.array'}, _id:0}}
])

我不知道如何通過 java 客戶端覆蓋它。

import org.springframework.data.mongodb.core.MongoTemplate;
...
Aggregation.newAggregation(
    Aggregation.project().andExclude("_id").???
)

在哪里可以找到用法?

這是測試文檔

public class TestArrayDocument {
    @Id
    String id;
    Integer[] x;
}

注入 MongoTemplate

@Autowired
MongoTemplate mongoTemplate;

這是聚合方法

  TypedAggregation<TestArrayDocument> aggregation  = Aggregation.newAggregation(TestArrayDocument.class,Aggregation
            .project()
            .andExclude("_id")
            .andExpression("first(x)").as("object"));

    List<Map> mapData=  mongoTemplate
            .aggregate(aggregation,Map.class)
            .getMappedResults();

x 是你的 $object.array。

在 LinkedHashMap 中返回“object”=>“firstElement”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM