Home > Enterprise >  How to get an item from an array inside Mongodb in java
How to get an item from an array inside Mongodb in java

Time:01-01

I'm completely new to creating an application in MongoDB. So I'm stuck with an issue where am not sure how to retrieve the items from inside the array in Mongodb. Following is the example

{
    "name": "Random Person",
    "age": 22,
    "address": "Address of the User",
    "likes":[{
        "like": 1,
        "comment": "Comment of the User",
        "description": "Some description"
    },
    {
        "like": 2,
        "comment": "Comment of the User",
        "description": "Some description"
    },
    {
        "like": 3,
        "comment": "Comment of the User",
        "description": "Some description"
    },
    ]
}

So the expected result that I want is the following

Name: Random Person
address: Address of the User
Comment: [Comment of the User, Comment of the User, Comment of the User] (Assuming we have different data at each index retrieved from Mongodb)

Following is the code

MongoCursor<Document> cursor = collection.find().iterator();
            
Document data = null;

while(cursor.hasNext()) {
    data = cursor.next();
    

    String name = (String) data.get("name");
    String address = (String) data.get("address");


    data.get("likes"); // Not sure about this line
}

I've tried using data.get("likes.comment"); but it return null as an output.

CodePudding user response:

This should do it:

data.getList("likes", Map.class)
        .stream()
        .map(map -> map.get("comment"))
        .collect(Collectors.toList());

I encourage you to read the Javadocs for the Java driver.

  • Related