How to write MongoDB Collection Filters for Child/Nested Objects in Java

271 views
Skip to first unread message

Dib

unread,
Mar 14, 2018, 9:48:20 PM3/14/18
to mongodb-user
Hi I am new to Mongo DB, can someone please help on this?

My MongoDB has collections of data as mentioned below. And I need to filter the collection using com.mongodb.client.model.Filters.
Can someone please let me know the syntax in Java, how filtering will look for such cases?

mytobecompare Java Object also have same structure.


 Bson queryParams = Filters.and(
 Filters.eq("my_data.count", mytobecompare.getCount()), //The filter for Count is okay.
 But what will be the Filters for "myslot" data structure that has list of objects(length and value).
 And I need to match all the collection data that has count 4, and myslot:[{length:1,value:A},{length:2,value:B},{length:3,value:C},{length:4,value:D}]
 

"my_data" : {
"count" : "4",
"myslot" : [
{
"length" : 1,
"value" : "A"
},
{
"length" : 2,
"value" : "B"
},
{
"length" : 3,
"value" : "C"
},
{
"length" : 4,
"value" : "D"
}
]
}

Dib

unread,
Mar 16, 2018, 9:48:03 PM3/16/18
to mongodb-user
Finally it got resolved.

 Here goes the sample code:                                                                          
   import com.fasterxml.jackson.databind.ObjectMapper;
     
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
public static <T> String convertObjectToJSON(final T messageObject) {
        try {
            return OBJECT_MAPPER.writeValueAsString(messageObject);
        } catch (IOException ex) {
            throw new IllegalStateException(ex);
        }
    }
...................................................................................
Filters.eq("my_data",  Document.parse(convertObjectToJSON(mytobecompare.getMyslotData()))))
Reply all
Reply to author
Forward
0 new messages