0
{
"_id" : ObjectId("5b4d975be2194da53a85e69f"),
"ISBN" : 2,
"book_title" : "ZERO TO ONE",
"author_name" : "Peter Theil",
"publisher" : "Penguin",
"status" : "ISSUED",
"issued" : [
    {
        "member_name" : "suresh",
        "member_id" : 101,
        "from_date" : "1/01/2018",
        "to_date" : "15/02/2018"
    },
    {
        "member_name" : "Jay",
        "member_id" : 103,
        "from_date" : "16/02/2018",
        "to_date" : "30/03/2018"
    }
]}

This is my Mongodb Document format.What i want to do is Count array length of issued of each document. So my Output will be Count:2 for this document. I want to implement this with spring data mongodb. I referred there documentation and found there is a Size class for this in ArrayOperators class Link here:

Spring data mongodb Documentaion

But i am don't know Use Size class ???

Mongodb terminal query is:

    db.library.aggregate([{$project:{count:{$size:"$issued"},"book_title":1,"_id":0}])

1 Answer 1

3

You can try below aggregation.

Using ArrayOperators

ProjectionOperation project = Aggregation.
            project("book_title").  
            andExclude("_id").
            and(ArrayOperators.arrayOf("issued").length()).as("count");

Using size helper method

ProjectionOperation project = Aggregation.
            project("book_title").
            andExclude("_id").
            and("issued").size().as("count");

Rest of aggregation

Aggregation aggregation = Aggregation.newAggregation(project);
List<Document> results = mongoTemplate.aggregate(aggregation, "library", Document.class).getMappedResults();
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.