java - MongoDB $lookup query returning empty field -
there 2 collections in database, projects
, tasks
. each project can have number of tasks associated it. trying create mongodb query in java return task
, embed project
linked it, code have completed far returns empty array (i have named something
appears []
below).
unfortunately have not found many examples on how use $lookup
in java. changes need perform on code something
field comes project
? should using $lookup
or aggregation operator?
the java method using mongo-java-driver version 3.5.0:
public static string readtask() { mongoclient mongoclient = new mongoclient(); mongodatabase database = mongoclient.getdatabase("exampledatabase"); bson lookup = new document("$lookup", new document("from", "project") .append("localfield", "project._id") .append("foreignfield", "_id") .append("as", "something")); list<bson> filters = new arraylist<>(); filters.add(lookup); aggregateiterable<document> = database.getcollection("task").aggregate(filters); system.out.println("first document: " + it.first().tostring()); return it.first().tostring(); }
this method returns following:
{ _id = 599a62cac29d9a2684c64012, constructionroomnumber = 15, type = example, summary = summary text, description = description text, status = open, project = { "$ref": "project", "$id": "5996582a0983347784fb2ff4" }, = [] }
expected result:
{ _id: objectid('599a62cac29d9a2684c64012') constructionroomnumber: "15" type: "example" summary: "summary text" description: "description text" status: "open" project: { _id: objectid('5996582a0983347784fb2ff4') projectcode: "v1000" projectname: "example project" projectlocation: "1 somewhere street, city" clientname: "whatever client" isactive: true } }
here example of data stored in mongodb looks like:
example project:
_id: objectid('5996582a0983347784fb2ff4') projectcode: "v1000" projectname: "example project" projectlocation: "1 somewhere street, city" clientname: "whatever client" isactive: true
example task:
_id: objectid('599a62cac29d9a2684c64012') constructionroomnumber: "15" type: "example" summary: "summary text" description: "description text" status: "open" project: dbref(project, 5996582a0983347784fb2ff4, undefined)
wiki
Comments
Post a Comment