简体   繁体   中英

How to query within a list of objects in mongodb with Java

I have a list of objects in Java. ChatDTO has a list of ChatReceiver.

The structure of ChatDTO is as follows:

public class ChatDTO {

@Id
String uuidMessage;
List<ChatReceiver> chatReceiver;


public ChatDTO() {
}

public List<ChatReceiver> getChatReceiver() {
    return chatReceiver;
}

public void setChatReceiver(List<ChatReceiver> chatReceiver) {
    this.chatReceiver = chatReceiver;
}


public String getUuidMessage() {
    return uuidMessage;
}

public void setUuidMessage(String uuidMessage) {
    this.uuidMessage = uuidMessage;
}

}

And the structure of ChatReceiver is as follows:

public class ChatReceiver {
String uuiUser;
Boolean received;
Date receivedDate;

public ChatReceiver() {
}

public String getUuiUser() {
    return uuiUser;
}

public void setUuiUser(String uuiUser) {
    this.uuiUser = uuiUser;
}

public Boolean getReceived() {
    return received;
}

public void setReceived(Boolean received) {
    this.received = received;
}

public Date getReceivedDate() {
    return receivedDate;
}

public void setReceivedDate(Date receivedDate) {
    this.receivedDate = receivedDate;
}
}

I need to query an element inside the list of ChatReceivers using Java, but I don't know how to do it correctly. I tried the following but I don't get the expected result.

List<AggregationOperation> list = new ArrayList<>();
            list.add(Aggregation.match(Criteria.where("chatReceiver").in(uuidReceiver).and("received").is(false).and("read").is(false)));
            TypedAggregation<ChatDTO> agg = Aggregation.newAggregation(ChatDTO.class, list);
            List<ChatDTO> chatDTOList = mongoOperations.aggregate(agg, ChatDTO.class, ChatDTO.class).getMappedResults();

As you could see, I need to get all ChatDTOs that contain a ChatReceiver that contains certain parameter (uuidUser) and where the boolean "received" is false. In other words, I need all ChatDTOs that haven't been received by certain user.

Can you help me with this query? I would appreciate it.

I need to get all ChatDTOs that contain a ChatReceiver that contains certain parameter (uuidUser) and where the boolean "received" is false. In other words, I need all ChatDTOs that haven't been received by certain user.

Sounds like you just need to use MongoDB Dot notation to query based on fields in the subdocument.

db.getCollection('chatDTO').find({
   "chatReceiver.uuiUser" : "test2", "chatReceiver.received" : false 
})

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