How to write Java ProjectionOperation computation

Doing projection operation dynamically to get field from nested documents. Projection from compass is working fine. Aggregation from mongo compass is


{
  "itemIds":{ $arrayElemAt: [{ $arrayElemAt: [{ $arrayElemAt: ['$Field1.field2.field3.itemIds',2]},2]},0]}
}

trying to get data using mongotemplate as following

ProjectionOperation projection = Aggregation.project().andExpression(Constants.NESTED_CATEGORY_ITEMIDS).as("itemIds").andExclude("_id");

using mongo template getting errors. Can you please suggest correct way to write projection computation using mongo template

HI @satishreddy,

Looking in this.

Kanika

I’m sure that it will be useful to show the definition for :arrow_up:
And also what error message you received.

Value of Constans.NESTED_CATEGORY_FIELDS is

{ $arrayElemAt: [{ $arrayElemAt: [{ $arrayElemAt: ['$Field1.field2.field3.itemIds',2]},2]},0]}

The Error I am getting is

Expression EL1043E: Unexpected token. Expected ‘rsquare(])’ but was 'comma(,) …

Actually I don’t know how to use Projections.computed to use with mongo template API. Please help me in how to write Mongo template API with Projections compute

It might be better to share a screenshot of the code and the full error message together.

Following is the code screen shot

values of variables are

From debugging values are

Constants.NESTED_CATEGORY_ITEMIDS is 

{ $arrayElemAt: [{ $arrayElemAt: [{ $arrayElemAt: ['$categories.subCategories.subCategories.itemIds',2]},2]},0]}

Constants.NESTED_CATEGORY_LEVEL is 

categories.2.subCategories.2.subCategories.0.itemIds

Constants.NESTED_CATEGORY_VALUE is

categories.subCategories.subCategories.subCategoryName

menuId  is 5e597a2be08a070bab329ef3

categoryName is Fish Taco

From debugging aggregation value is

{ "aggregate" : "__collection__", "pipeline" : [{ "$match" : { "_id" : { "$oid" : "5e597a2be08a070bab329ef3" }, "categories.subCategories.subCategories.subCategoryName" : "Fish Taco" } }, { "$project" : { "subCategories.subCategories.itemIds',2]},2]},0]}}]}" : "$categories.subCategories.subCategories.itemIds',2]},2]},0]}}]}" } }] } 

after running mongotemplate aggregate with following payload

I am getting following error

Please help me in writing projections to get the Constants.NESTED_CATEGORY_ITEMIDS

Hi @satishreddy,

As this is not covered in our course, here is the community forums where you can get help:

Kanika