On Fri, 20 Sep 2013 06:16:03 GMT, Sönke Ludwig wrote:

On Thu, 19 Sep 2013 21:07:37 GMT, Craig Dillabaugh wrote:

Hello,

I have a JSON document read in from MongoDB and want to access some field that contains another Json object (as a child) and an array of Json objects as another child. The key for the field is called 'gtlayer' in my particular document. I can access this object in the Mongo client using the following:

clip

Craig

Okay, so cur_proj will iterate over all documents in the "projects" collection and each returned Bson document will have the form {"_id": ObjectID(...), "gtlayer": ...}. So to get the gtlayer.shapes field, you could just do the following:

auto cur_proj = projects.find( Bson.EmptyObject, ["gtlayer": 1] ); \\Get a cursor to the database.
foreach (bs; cur_proj) {
    assert(!bs.gtlayer.isNull());
    auto shapes = bs.gtlayer.shapes.get!(Bson[]);
    Shape[] ret = shapes.map!(deserializeBson!Shape).array;
    // ...
}

If you only ever have a single document in the collection, or intend to find just a single one, findOne would be the right approach:

auto bs = projects.findOne(Bson.EmptyObject, ["gtlayer": 1]);
enforce(!bs.isNull(), "Couldn't find project");
assert(!bs.gtlayer.isNull());
auto shapes = bs.gtlayer.shapes.get!(Bson[]);
Shape[] ret = shapes.map!(deserializeBson!Shape).array; 
// ...

That is assuming that Shape can be Bson (de)serialized properly (i.e. it either has all fields publicly accessible or has read/write properties for each of them or has fromBson/toBson methods).

...it's very possible that I got something totally wrong about the problem, though. I'll try again if this doesn't make sense ;)

Thanks. Everything works up to the last step where I get the following:

source/app.d(137): Error: template instance shapes!(map(deserializeBson!(Shape))) shapes is not a template declaration, it is a variable
source/app.d(137): Error: template instance shapes!(map(deserializeBson!(Shape))) shapes is not a template declaration, it is a variable

Where line 137 is the line Shape[] ret = shapes.map!(deserializeBson!Shape).array, which I figure I should be able to fix, but I have no idea where the map!(...).array bit comes from.

Cheers,
Craig