MongoDB
 SQL >> Base de Dados >  >> NoSQL >> MongoDB

Converter um comando de agregação do MongoDB para código Java

Há dois problemas. Primeiro, asList("$modifiedon",1000) deveria ser asList("$modifiedon","$createdon"). Segundo, e mais importante, then e else estão sendo anexados ao documento de $gt, quando deveriam ser anexados ao if.

Correção:

AggregateIterable iterable = collection.aggregate(
  asList(
    new Document("$redact",
      new Document("$cond",
        new Document("if",
          new Document("$gt",
            asList(
              new Document("$subtract", asList("$modifiedon", "$createdon")),
              1000 * 60 * 60 * 24
            )
          )
        )
        .append("then", "$$KEEP")
        .append("else", "$$PRUNE")
      )
    )
  )
);

O ponto central é que $cond recebe if, then e else como chaves irmãs.