1

I have an Article document class like.

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;
//    }
}

I am using aggregation pipeline to select only author and dot of the documents as:

{
    author: 1,
    dot: 1
}

Aggregation is done like:

Aggregation aggregation = newAggregation(Article.class,
            aggregate("$project",
                    projection),
                    sort(Sort.Direction.DESC, "dot")
);
return mongoTemplate.aggregate(aggregation, "article", Article.class);

But I am getting the API response as:

{
    "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
},

I want only the non null fields as output. I can do it by defining a new POJO class for the required fields only, but Is there a way to do it without defining new classes(It will be a nightmare if the projection is a parameter of the API only)?

1 Answer 1

4

Add jackson annotation @JsonInclude for removing null fields.

@JsonInclude(Include.NON_NULL)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.