Andrii Abramov
Andrii Abramov

Reputation: 10783

Get array element from MongoDB using Spring Data Mongo

I want to retrieve an array from MongoDB using Spring Data Mongo.

I have collection consists of users with todos:

{
    "_id" : ObjectId("584d863e439e512f4c457eea"),
    "username" : "e",
    "todos" : [
        {
            "_id" : ObjectId("584d8654439e512f4c457eeb"),
            "title" : "Officiis id sed aut molestiae id id magni.",
            "body" : "Fugit velit rem incidunt. Et ad aliquam inventore voluptatem sed omnis voluptas. Aut sint eum voluptatem.",
            "when" : ISODate("1972-09-15T04:24:08.880Z"),
            "priority" : "HIGH",
            "status" : "DEFAULT",
            "tags" : [
                "animi",
                "veniam",
                "exercitationem"
            ]
        },
        // ...
    ]
}

I have tried the following:

public List<Todo> getUserTodos(String userId)
    Query x = new Query(Criteria.where("_id").is(userId));
    x.fields().exclude("_id").include("todos");
    return mongoTemplate.find(x, Todo.class);
}

Actually, I am getting an empty ArrayList. The response in mongo cli is like:

{
    "todos": [ {/* todo1 */}, {/* todo2 */} ]
}

How to return array from MongoDB or how to unwrap it for deserializing in Java?

Upvotes: 0

Views: 3114

Answers (1)

Rahul Kumar
Rahul Kumar

Reputation: 2831

Well it would always return the document and not just a part of the document, when you include the field "todo" you just ensure that, that field is returned and others aren't but still it is the document which will be returned which will contain value "todos".

If you pass Todo.class it will look into a collection called todo, which isn't there, hence the empty list.

public List<Todo> getUserTodos(String userId)
    Query x = new Query(Criteria.where("_id").is(userId));
    x.fields().exclude("_id").include("todos");
    User user = mongoTemplate.findOne(x, User.class);
    return user.getTodos();
}

This same thing can be done with a map

public List<Todo> getUserTodos(String userId)
    Query x = new Query(Criteria.where("_id").is(userId));
    x.fields().exclude("_id").include("todos");
    Map user = mongoTemplate.findOne(x, Map.class);
    if(user != null && user.containsKey("todos")){
      return (List<Todo>)user.get("todos");
    }
    return null;
}

Upvotes: 1

Related Questions