私は次の文書構造を持っています (これは理解を目的としたダミー文書です)
{
"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"
}
]
}
これらのドキュメントから「cloth_type」を投影したいので、次のJavaコードを試しました
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());
}
(ここでは「$unwind」は使いたくない)
次の出力を取得します。
{ "id" : "p1245" , "ClothType" : [ "C" , "J" , "T"]}
{ "id" : "p124576" , "ClothType" : [ "C"]}
単一の ID に複数の「cloth_type」がある場合cloth_type
、この配列の最後のものだけが必要です。たとえば、「ClothType
」[「C」、「J」、「T」]の配列がある場合、[「T」]、つまり配列の最後の要素のみを投影したい。「$ unwind」を使用せずにこれを達成する方法はありますか。