简体   繁体   中英

How to get a a property in a property from a dbobject in java, mongodb

So I have a few dbobjects in my mongo database. Here's an example of one of the objects:

{ "_id" : { "$oid" : "525b048580c3fb0d62d2b6fc"} , "city" : "London" , "currentWeather" : [ { "cloudcover" : "25"      , "humidity" : "82" , "observation_time" : "08:37 PM" , "precipMM" : "0.0" , "pressure" : "1008" , "temp_C" : "11" ,    "temp_F" : "52" , "visibility" : "10" , "weatherCode" : "113" , "weatherDesc" : [ { "value" : "Clear"}] , "weatherIconUrl" : [ { "value" : "http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0008_clear_sky_night.png"}] , "winddir16Point" : "W" , "winddirDegree" : "280" , "windspeedKmph" : "19" , "windspeedMiles" : "12"}]}

Now, I need to get all the dbobjects in my database whose value is lower than a given "temp_C", I have used something like this:

BasicDBObject query = new BasicDBObject("temp_C", new BasicDBObject("&gt", graden));

But it's failing, and I think it is because the property is a subproperty of "currentWeather", yet I have no idea how to address this problem. I am using java to do this.

Looking at your document structure, you're trying to access a subdocument that lives inside an array in your document, so it's a bit more complicated than a standard query:

{ "_id" : { "$oid" : "525b048580c3fb0d62d2b6fc"} , <-- Document
  "city" : "London" , 
  "currentWeather" : [                             <-- Array
                         { "cloudcover" : "25",    <-- Sub document
...etc...
                           "pressure" : "1008" , 
                           "temp_C" : "11",
                           "temp_F" : "52", 
...etc...
                         }
                     ]
}

In order to get to the nested object, you need to reference its position in the array (in this case, it's zero as it's the first element in the array) and then the field name in the sub document. So your query looks like this:

BasicDBObject query = new BasicDBObject("currentWeather.0.temp_C", 
                                        new BasicDBObject("$gt", 11));

Note you had two problems in your original query:

1) You need to reference currentWeather.0.temp_C 2) Your gt operator needs to start with a dollar sign not an ampersand.

Also, you said you wanted the query to return values lower than a given value, in which case you probably want $lt not $gt.

You can't directly use the value of the object of an array in a query. You can use aggregate framework of Mongo. Java Docs For Aggregate are here

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