U kunt $expr gebruiken ( 3.6 mongo-versie-operator ) om aggregatiefuncties te gebruiken in reguliere zoekopdrachten.
Vergelijk query operators
vs aggregation comparison operators
.
Gebruik $indexOfArray
operator om de $max
. te vinden bijgewerkt tijdstempelelement in statusarray gevolgd door het projecteren van de statuswaarde en vergelijking om de waarde te vergelijken met de invoerstatus.
Shell-query is dus
{
"key":"56h68ab4c876dbe1cd0b1ee",
"$expr":{
"$eq":[
{"$let":{
"vars":{
"status":{"$arrayElemAt":["$status",{"$indexOfArray":["$status.updatedTimeStamp",{"$max":"$status.updatedTimeStamp"}]}]}
},
"in":"$$status.orderStatus"
}},
"CONFIRM_PAYMENT"]
}
}
Lentecode:
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);
Mongo 3.4 klachtversie:
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}}
])
Lentecode:
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);