0

I have following document structure (This is dummy document for understanding purpose)

{ 
    "id" : "p1245", 
    "Info" : [             
        { 
            "cloth_name" : "ABC", 
            "cloth_type" : "C"
        },
        { 
            "cloth_name" : "PQR", 
            "cloth_type" : "J"
        },
        { 
            "cloth_name" : "SAM", 
            "cloth_type" : "T"
        }
    ] 
},
{ 
    "id" : "p124576", 
    "Info" : [             
        { 
            "cloth_name" : "HTC", 
            "cloth_type" : "C"
        }
    ]
}

From these document I want to project the "cloth_type", so I tried following java code

    DBObject fields = new BasicDBObject("id", 1);
    fields.put("ClothType","$Info.cloth_type");
    DBObject project = new BasicDBObject("$project", fields);
    List<DBObject> pipeline = Arrays.asList(project);
    AggregationOptions aggregationOptions = AggregationOptions.builder().batchSize(100).outputMode(AggregationOptions.OutputMode.CURSOR).allowDiskUse(true).build();
    Cursor cursor = collection.aggregate(pipeline, aggregationOptions);
    while (cursor.hasNext()) 
    {
        System.out.println(cursor.next());
    }

(I don't want to use "$unwind" here)

and get following output:

{ "id" : "p1245" , "ClothType" : [ "C" , "J" , "T"]}
{ "id" : "p124576" , "ClothType" : [ "C"]}

If there are multiple "cloth_type" for single id, then I want only the last cloth_type from this array. I want something like, e.g. if there is array of "ClothType" [ "C", "J", "T"] then I want to project only [ "T"] i.e last element of array. Is there any ways to achive this without using "$unwind".

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
PKH
  • 47
  • 1
  • 2
  • 6

0 Answers0