user1053031 user1053031 - 2 months ago 11
JSON Question

Search in complex documents in mongo db

Assume i have the following document in Mongo:

{
"_id" : ObjectId("57e36c34eb2832aa68b39b26"),
"ap_domain" : "root",
"average_down" : 123,
"average_up" : 234,
"peak_down" : 123,
"peak_up" : 456,
"ssid_shaper_list" :
{
"SSID1" : {
"ssid_domain" : "root",
"peak_up" : 456,
"peak_down" : 456
},
"SSID2" : {
"ssid_domain" : "root",
"average_up" : 567,
"average_down" : 567,
"peak_up" : 456,
"peak_down" : 456
}
}
}


I need to check that
SSID2
exists in this document. Here I have 3 keys:

1. ap_domain = root
2. ssid_shaper_list = SSID2 and in it:
3. ssid_domain = root


How should i compose my search criteria in java using BasicDBObject to check that needed SSIDi exists?

Answer

The following query contains all your search conditions:

DBObject query = new BasicDBObject("ap_domain", "root").append("ssid_shaper_list.SSID2.ssid_domain", "root");

You don't need to check if SSID2 exists in ssid_shaper_list as the second part of the query implicitly does that.

The following query can be used to fetch documents that have SSID2 object in the ssid_shaper_list array.

DBObject query = new BasicDBObject("ssid_shaper_list.SSID2", new BasicDBObject("$exists", true));
Comments