Pillola 10: Utilizzo di dateAsFormattedString in Spring Data Mongodb

Pubblicato il 04/11/2022

Problema:

Come utilizzo la funzione $dateToString presente in MongoDB in Spring Data ?

db.presence.aggregate(
[ 
    { 
        "$group" : {
            "_id" : {
                "date" : { $dateToString: { format: "%d-%m-%Y", date: "$date"}}, 
                "sensorId" : "$sensorId",
            },
             count: { $sum: 1 }   
        }
    }

]);

Soluzione

Utilizzando il metodo dateAsFormattedString della classe ProjectOperationBuilder

List<AggregationOperation> operations = new ArrayList<AggregationOperation>();
operations.add(
	Aggregation.project("sensorId").andExpression("date").dateAsFormattedString("%d-%m-%Y").as("date"));
operations.add(Aggregation.group("sensorId", "date").count().as("count"));
Aggregation aggregation = Aggregation.newAggregation(operations);
AggregationResults<Metrics> result = mongo.aggregate(aggregation, PresenceDocument.class, Metrics.class);
@Document(collection = "presence")
public class PresenceDocument {
	@Id
	private String id;
	private String sensorId;
	private ZonedDateTime date;

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getSensorId() {
		return sensorId;
	}

	public void setSensorId(String sensorId) {
		this.sensorId = sensorId;
	}

	public ZonedDateTime getDate() {
		return date;
	}

	public void setDate(ZonedDateTime date) {
		this.date = date;
	}
}

public class Metrics {
	private GroupId id;
	private int count;

	public static class GroupId {
		private String date;
		private String sensorId;

		public String getDate() {
			return date;
		}

		public void setDate(String date) {
			this.date = date;
		}

		public String getSensorId() {
			return sensorId;
		}

		public void setSensorId(String sensorId) {
			this.sensorId = sensorId;
		}
	}

	public GroupId getId() {
		return id;
	}

	public void setId(GroupId id) {
		this.id = id;
	}

	public int getCount() {
		return count;
	}

	public void setCount(int count) {
		this.count = count;
	}

}

  • I contenuti di questo articolo sono rilasciati con licenza CC-BY 4.0
  • Eventuali spezzoni di codice presentati seguono, dove non dichiarato, licenza MIT