Reputation: 747
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?
Upvotes: 1
Views: 134
Reputation: 1374
I think you can simplify your search criteria by combining 2. and 3. so your query would look like:
{ap_domain: 'root', 'ssid_shaper_list.SSID2.ssid_domain': 'root'}
The second key uses dot notation to specify embedded documents, more info here
Depending upon your mongo driver version you may want to use QueryBuilder (pre 3.0) which will return a [Basic]DBObject, or Filters (3.0+) which will give you Bson that can still be used the same way for queries and looks cleaner.
Upvotes: 1
Reputation: 5095
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));
Upvotes: 2
Reputation: 3554
The match of ssid_domain = root already implies that SSID2 is present. Thus, you have:
Filters.and(
Filters.eq("ap_domain", "root"),
Filters.eq("ssid_shaper_list.SSID2.ssid_domain", "root"));
Use that filter in the MongoCollection.find() method.
Upvotes: 1