I have following mongodb document structure
{
"_id": ObjectId("571530da41995a703faaf55b"),
"project_name": "abc",
"status": "new",
"cluster": "",
"sku": {
"_id": "57152f7941995a703faaf559",
"name": "temp",
"distribution": "apache",
"creation_date": "2016-04-18T19:02:46.595Z",
"user_id": "570784b1682d25f45b64ed51",
"__v": 0,
"services": []
}
}
I want to find project info given a sku._id. I am using following piece of code for this purpose.
String getProjectIDforSku(String skuID ) {
ObjectId id = new ObjectId(skuID);
BasicDBObject query = new BasicDBObject("sku", new BasicDBObject("_id", skuID));
DBObject obj = getCollection("deployment", "projects").findOne(query);
if (obj != null) {
var jsonString = Json.parse(obj.toString());
return jsonString;
} else
return null;
}
When I call this function, I receive null instead of valid json string. Can anyone guide me where i am wrong? Thanks
Change
BasicDBObject query = new BasicDBObject("sku", new BasicDBObject("_id", skuID));
to
BasicDBObject query = new BasicDBObject("sku._id",skuID);
The reason being that in the first one you are comparing sku to an object with only one field _id (which is not the case, the object has other fields), while the second one only matches the _id field within the sku object.