简体   繁体   中英

How to get an item from an array inside Mongodb in java

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM