我有以下文档结构(这是用于理解目的的虚拟文档)
{
"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”的情况下实现这一点。