I would like to make an aggregate with Spring Data MongoDB and I don't know how to make this group stage :
$group: {
_id: {
field1: "$field1",
field2: "2017-06-21",
field3: "$field3"
},
...
}
I don't know how to put the constant date into the second field of the _id
For the moment i do this :
groupOperation = group("field1","field3")
But i'm not sure that it make a group stage on the value of fields and i don't no how put a new field into _id.
I don't find good doc about the operation of different stage of an aggregate in Spring data MongoDB
If someone has an idea I'm interested
Thank you in advance
答案 0 :(得分:0)
Here is an example of using multiple fields on group
and count
the values.
Aggregation aggregate = Aggregation.newAggregation(Aggregation.group("category", "status").count().as("Categoury_Status_Count"));
AggregationResults<String> aggregateResult = mongoOperations.aggregate(aggregate, "category", String.class);
System.out.println(aggregateResult.getMappedResults());
My Sample Data:-
/* 1 */
{
"_id" : 1,
"category" : "cafe",
"status" : "A"
}
/* 2 */
{
"_id" : 2,
"category" : "cafe",
"status" : "B"
}
/* 3 */
{
"_id" : 3,
"category" : "cafe1",
"status" : "A"
}
/* 4 */
{
"_id" : 4,
"category" : "cafe1",
"status" : "B"
}
/* 5 */
{
"_id" : 5,
"category" : "cafe1",
"status" : "B"
}
Output:-
[{ "category" : "cafe1" , "status" : "A" , "Categoury_Status_Count" : 1}, { "category" : "cafe" , "status" : "B" , "Categoury_Status_Count" : 1}, { "category" : "cafe1" , "status" : "B" , "Categoury_Status_Count" : 2}, { "category" : "cafe" , "status" : "A" , "Categoury_Status_Count" : 1}]
To get the _id in the output:-
You can add the _id to the set.
Aggregation aggregate = Aggregation.newAggregation(Aggregation.group("category", "status").count().as("Categoury_Status_Count").addToSet("_id").as("ids"));
Output:-
[{ "category" : "cafe1" , "status" : "A" , "Categoury_Status_Count" : 1 , "ids" : [ 3.0]}, { "category" : "cafe" , "status" : "B" , "Categoury_Status_Count" : 1 , "ids" : [ 2.0]}, { "category" : "cafe1" , "status" : "B" , "Categoury_Status_Count" : 2 , "ids" : [ 5.0 , 4.0]}, { "category" : "cafe" , "status" : "A" , "Categoury_Status_Count" : 1 , "ids" : [ 1.0]}]
答案 1 :(得分:0)
Fields fields = Fields.fields("field1", "field2", "field3");
GroupOperation groupOp = Aggregation.group(fields);
这将导致组阻止
$group: {
_id: {
field1: "$field1",
field2: "$field2",
field3: "$field3"
}