Check for sub field existence in Mongodb java driver -


i'm using mongodb version 3.4, java driver.

i have collection of jsons of format:

{     "foo": {     "d4231ds": {         "type":"a",         "color":"red"     },     "dmncxa3s": {         "type":"b",         "color":"yellow"     },      "jsdjs8": {         "type":"a",         "color":"red"     },      "skjdcxar3": {         "type":"c",         "color":"green"     }     },     "bar": "100011" } 

i need documents have "type":"a", using java. keys under foo (d4231ds,dmncxa3s etc) aren't known in advance, , differ between documents. hence, using dot operator not working in case.

i've tried looking on several methods, non seemed achieve this.

you can try below aggregation in latest 3.4 server version.

use $objecttoarray convert named keys key value pair ( k, v ) , use $in query value document field type = a.

$redact acts on results query filter, $$keep when match else $$prune

 mongoclient mongoclient = new mongoclient();  mongodatabase database = mongoclient.getdatabase(db_name);  mongocollection<document> mongocollection = database.getcollection(collection_name);  document query = document.parse("{\"$redact\":{\"$cond\":[{\"$let\":{\"vars\":{\"subelems\":{\"$objecttoarray\":\"$foo\"}},\"in\":{\"$in\":[\"a\",\"$$subelems.v.type\"]}}},\"$$keep\",\"$$prune\"]}}");  list<document> result = mongocollection.aggregate(arrays.aslist(query)).into(new arraylist<>()); 

mongo shell query:

db.collection_name.aggregate([   {     "$redact": {       "$cond": [         {           "$let": {             "vars": {               "subelems": {                 "$objecttoarray": "$foo"               }             },             "in": {               "$in": [                 "a",                 "$$subelems.v.type"               ]             }           }         },         "$$keep",         "$$prune"       ]     }   } ]) 

Comments

Popular posts from this blog

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

python Tkinter Capturing keyboard events save as one single string -

sql server - Why does Linq-to-SQL add unnecessary COUNT()? -