【发布时间】:2020-04-24 18:23:01
【问题描述】:
我有一个 Article 文档类,例如。
package com.document.feed.model;
import java.util.List;
import org.bson.types.ObjectId;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.lang.NonNullFields;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
class Source {
private String id;
private String name;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
@Document
@Getter
@Setter
@JsonIgnoreProperties(ignoreUnknown = true)
public class Article {
@Id
private String id;
private Source source;
private String author;
private String title;
private String description;
private String url;
private String urlToImage;
private String publishedAt;
private String content;
private String country;
private String category;
// Vector of Tf-Idf weights.
private List<Double> v;
// Extra fields computed during ordering.
private double dot;
// public Article(String id, String author, Double dot) {
// this.id = id;
// this.author = author;
// this.dot = dot;
// }
}
我正在使用聚合管道仅选择 author 和 dot 的文档为:
{
author: 1,
dot: 1
}
聚合完成如下:
Aggregation aggregation = newAggregation(Article.class,
aggregate("$project",
projection),
sort(Sort.Direction.DESC, "dot")
);
return mongoTemplate.aggregate(aggregation, "article", Article.class);
但我得到的 API 响应为:
{
"id": "5e137c67771a9880d1639b5d",
"source": null,
"author": "Asian News International",
"title": null,
"description": null,
"url": null,
"urlToImage": null,
"publishedAt": null,
"content": null,
"country": null,
"category": null,
"v": null,
"dot": 3.2454110250954025
},
我只想要非空字段作为输出。我可以通过只为必填字段定义一个新的 POJO 类来做到这一点,但是有没有办法在不定义新类的情况下做到这一点(如果投影只是 API 的参数,那将是一场噩梦)?
【问题讨论】:
标签: spring mongodb aggregation-framework spring-webflux spring-mongodb