The Java MongoTemplate query returns a specified field and a specified amount of data

suppose I have an entity class Article

@Data
@Document(collection = "articles")
public final class Article {
    @Id
    private String id;
    private String name;
    private String url;
    private String author;
    private List<Comment> comments;
}

entity class Comment

@Data
public final class Comment {
    private String userId;
    private String content;
}

has added several pieces of data through the test case. Assume that the _ id of one of the Article is 5b5694f38ec9b636c4e52d69 , and the
can obtain the Article, of this id through MongoRepository , or through MongoTemplate ,

.
final String id = "5b5694f38ec9b636c4e52d69";
Query query = new Query()
              .addCriteria(Criteria.where("id").is(id));
Article article = mongoTemplate.findOne(query, Article.class);

so you can get it. Now I just want to get the List < Comment >,

of this Article.
Document queryObject = new Document();
queryObject.put("id", id);

Document fieldsObject = new Document();
fieldsObject.put("id", false);
fieldsObject.put("comments", true);

Query query = new BasicQuery(queryObject, fieldsObject);

if I return List when I find

List comments = mongoTemplate.findOne(query, List.class);

there is no doubt that an exception will occur. Return Article

Article article = mongoTemplate.findOne(query, Article.class);
List<Comment> comments = Optional.of(article).orElseThrow(ArticleNotFoundException::new)
                                            .getComments();

this allows you to get List < Comment > , but it doesn"t make much sense to get a specified number of Commit (subList ().
is there any way to return List < Commit > directly so that you can use limit () and skip () ; if not, is there a way to achieve the same effect as limit () skip () ?

Mar.29,2021

found the answer by looking up the document

MongoCollection<Document> collection =
    mongoClient.getDatabase(YOUR_DATABASE_NAME).getCollection(YOUR_COLLECTION_NAME);
FindIterable<Document> findIterable = collection.find()
                                                .filter(eq("_id", new ObjectId(id)))
                                                .projection(fields(include("comments"), excludeId(), slice("comments", 2)));
Document document = findIterable.first();
if (document != null) {
    Object o = document.get("comments");
    if (o instanceof List) {
        List comments = (List) o;
        assert comments.size() == 2;
    }
}

from-query-results/-sharpproject-specific-array-elements-in-the-returned-array" rel=" nofollow noreferrer "> MongoDB document

Menu