I have the following data which I am quering on:
[
{
"_id": 1,
"domainName": "test1.com",
"hosting": "hostgator.com",
"to": "nanjing",
"travelDate": "09/06/2022",
"trainNumber": 123
},
{
"_id": 2,
"domainName": "test2.com",
"hosting": "aws.amazon.com",
"to": "beijing",
"travelDate": "09/02/2022",
"trainNumber": 123
},
{
"_id": 3,
"domainName": "test3.com",
"hosting": "aws.amazon.com"
},
{
"_id": 4,
"domainName": "test4.com",
"hosting": "hostgator.com",
"to": "shanghai",
"travelDate": "09/06/2022",
"trainNumber": 1234
},
{
"_id": 5,
"domainName": "test5.com",
"hosting": "aws.amazon.com",
"to": "wuhan",
"travelDate": "09/06/2022",
"trainNumber": 1234
},
{
"_id": 6,
"domainName": "test6.com",
"hosting": "cloud.google.com",
"to": "nanjing",
"travelDate": "09/06/2022",
"trainNumber": 123
},
{
"_id": 7,
"domainName": "test7.com",
"hosting": "aws.amazon.com",
"to": "nanjing",
"travelDate": "09/02/2022",
"trainNumber": 123
},
{
"_id": 8,
"domainName": "test8.com",
"hosting": "hostgator.com",
"to": "nanjing",
"travelDate": "09/02/2022",
"trainNumber": 123
},
{
"_id": 9,
"domainName": "test9.com",
"hosting": "cloud.google.com",
"to": "nanjing",
"travelDate": "09/02/2022",
"trainNumber": 123
},
{
"_id": 10,
"domainName": "test10.com",
"hosting": "godaddy.com",
"to": "nanjing",
"travelDate": "09/02/2022",
"trainNumber": 123
}
]
I am using the following query to get the filed to as a list of string
db.collection.aggregate({
$match: {
travelDate: {
$eq: "09/06/2022"
},
trainNumber: {
$eq: 1234
}
}
},
{
$group: {
_id: "",
destStations: {
$push: "$to"
}
}
},
{
$project: {
_id: 0
}
})
The above query returns the following result as expected:
[
{
"destStations": [
"shanghai",
"wuhan"
]
}
]
But when I am trying to convert it using the following spring mongo aggregation I cannot get the appropriate result. Can anyone help?
Aggregation agg = newAggregation( match(Criteria.where("travelDate").is(travelDate).and("trainNumber").is(trainNumber)),
group("id").push("to").as("destStations"),
project().andExclude("id")
);
CodePudding user response:
You are grouping by id
, in your spring mongo aggregation, but in your query it's you are grouping on ""
empty string. That's why the results might be varying.
Try passing no argument to group
function, like this:
Aggregation agg = newAggregation(match(Criteria.where("travelDate").is(travelDate).and("trainNumber").is(trainNumber)),
group().push("to").as("destStations"),
project().andExclude("id")
);