Můžete použít $expr (operátor verze 3.6 mongo) pro použití agregačních funkcí v běžném dotazu.
Porovnejte query operators
vs aggregation comparison operators
.
Použijte $indexOfArray
operátor najít $max
aktualizovaný prvek časového razítka ve stavovém poli následovaný promítnutím hodnoty stavu a porovnáním pro kontrolu hodnoty se stavem vstupu.
Shell dotaz je tedy
{
"key":"56h68ab4c876dbe1cd0b1ee",
"$expr":{
"$eq":[
{"$let":{
"vars":{
"status":{"$arrayElemAt":["$status",{"$indexOfArray":["$status.updatedTimeStamp",{"$max":"$status.updatedTimeStamp"}]}]}
},
"in":"$$status.orderStatus"
}},
"CONFIRM_PAYMENT"]
}
}
Jarní kód:
Query query = new BasicQuery("{key:'56h68ab4c876dbe1cd0b1ee','$expr':{'$eq':[{$let:{vars:{status:{'$arrayElemAt':['$status',{'$indexOfArray':['$status.updatedTimeStamp',{'$max':'$status.updatedTimeStamp'}]}]}}, in:'$$status.orderStatus'}},'CONFIRM_PAYMENT']}}");
List<Document> results = mongoTemplate.find(query, Document.class);
Verze reklamace Mongo 3.4:
Shell Query:
db.order.aggregate([
{ "$match" : { "key" : "56h68ab4c876dbe1cd0b1ee"}} ,
{ "$addFields" : {
"cmpret" : {
"$eq" : [
{ "$let" : {
"vars" : { "status" : { "$arrayElemAt" : [ "$status" , { "$indexOfArray" : [ "$status.updatedTimeStamp" , { "$max" : "$status.updatedTimeStamp"}]}]}} ,
"in" : "$$status.orderStatus"
}} ,
"CONFIRM_PAYMENT"
]
}
}} ,
{ "$match" : { "cmpret" : true}} ,
{ "$project" : { "cmpret" : 0}}
])
Jarní kód:
AggregationOperation match1 = Aggregation.match(Criteria.where("key").is("56h68ab4c876dbe1cd0b1ee"));
AggregationOperation addFields = new AggregationOperation() {
@Override
public Document toDocument(AggregationOperationContext aggregationOperationContext) {
Document cmpret = Document.parse("{'$eq':[{$let:{vars:{status:{'$arrayElemAt':['$status',{'$indexOfArray':['$status.updatedTimeStamp',{'$max':'$status.updatedTimeStamp'}]}]}}, in:'$$status.orderStatus'}},'CONFIRM_PAYMENT']}}");
return new Document("$addFields", new Document("cmpret", cmpret));
}
};
AggregationOperation match2 = Aggregation.match(Criteria.where("cmpret").is(true));
AggregationOperation dropFields = new AggregationOperation() {
@Override
public Document toDocument(AggregationOperationContext aggregationOperationContext) {
return new Document("$project", new Document("cmpret", 0));
}
};
Aggregation aggregation = Aggregation.newAggregation(
match1,
addFields,
match2,
dropFields
);
AggregationResults<Document> results = mongoTemplate.aggregate(aggregation, "order", Document.class);