投影mongodb时如何获取最后一个数组元素
我有以下文档结构(这是用于理解目的的虚拟文档) 从这些文档中,我想投影“cloth_类型”,所以我尝试了以下java代码投影mongodb时如何获取最后一个数组元素,mongodb,aggregation-framework,mongo-java-driver,Mongodb,Aggregation Framework,Mongo Java Driver,我有以下文档结构(这是用于理解目的的虚拟文档) 从这些文档中,我想投影“cloth_类型”,所以我尝试了以下java代码 DBObject fields = new BasicDBObject("id", 1); fields.put("ClothType","$Info.cloth_type"); DBObject project = new BasicDBObject("$project", fields); List<DBObject> pipe
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());
}
如果单个id有多个“cloth_type”,那么我只需要此数组中最后一个cloth_type
。
我想要类似这样的东西,例如,如果存在“ClothType
”[“C”、“J”、“T”]的数组,那么我只想投影[“T”],即数组的最后一个元素。
是否有任何方法可以在不使用“$unwind”的情况下实现此目的。为什么不使用
$unwind
?是否将最后一次元素检索放入聚合查询本身?你为什么不用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());
}
{ "id" : "p1245" , "ClothType" : [ "C" , "J" , "T"]}
{ "id" : "p124576" , "ClothType" : [ "C"]}