Here is my Query,
db.product.aggregate([
{ $match : {categoryID : 4 } },
{ "$group" : { "_id" : { "productID": "$productID",
"articleID": "$articleID", "colour":"$colour",
"set&size": { "sku" : "$skuID", "size" : "$size" },
},
}
},
{ "$group" : { "_id" : { "productID": "$_id.productID", "colour":"$_id.colour" },
"size": { "$addToSet" : { "sku" : "$_id.set&size.sku",
"size" : "$_id.set&size.size" }
},
}
},
{"$project":{
"_id":0,
"productID": "$_id.productID",
"colour":"$_id.colour",
"size":"$size",
}
},
]);
By executing this query on mongo shell i get perfect output.
output
{
"_id": {
"productID": "PRD1523",
"colour": "GREEN"
},
"size": [
{
"sku": "ALT50095",
"size": "S"
},
{
"sku": "ALT50096",
"size": "XL"
}
]
}
{
"_id": {
"productID": "PRD1523",
"colour": "RED"
},
"size": [
{
"sku": "ALT50094",
"size": "M"
},
{
"sku": "ALT50093",
"size": "S"
}
]
}
but when with my java code it gives exception.
Here is java code for above query,
DBCollection table = mongoTemplate.getCollection(collection_name);
BasicDBObject matchTopics = new BasicDBObject();
matchTopics.put("categoryID", 4);
DBObject groupSameIdEntities = new BasicDBObject("_id", new BasicDBObject("productID", "$productID")
.append("articleID", "$articleID").append("colour", "$colour")
.append("set&size", new BasicDBObject("sku", "$skuID").append("size", "$size")));
DBObject secondGroup = new BasicDBObject("_id", new BasicDBObject("colour", "$_id.colour").append("productID",
"$_id.productID").append(
"size",
new BasicDBObject("$addToSet", new BasicDBObject("sku", "$_id.set&size.sku").append("size",
"$_id.set&size.size"))));
AggregationOutput output = table.aggregate(new BasicDBObject("$match", matchTopics), new BasicDBObject(
"$group", groupSameIdEntities), new BasicDBObject("$group", secondGroup));
Exception
HTTP Status 500 - Request processing failed; nested exception is com.mongodb.CommandFailureException: { "serverUsed" : "127.0.0.1:27017" , "errmsg" : "exception: invalid operator '$addToSet'" , "code" : 15999 , "ok" : 0.0}
I can't figure out how to solve this error.