Reputation: 1182
Here is my code in mongodb : .
db.mydb.aggregate([
{ "$group": {
"_id": {
"A": "$A",
"B": "$B",
"C": "$C"
},
}},
{ "$group": {
"cpt": { '$sum': 1 } ,
"_id": "$_id.A",
"allowDrag": {'$literal':false},
"expanded": {'$literal':false},
"children": {
"$push": {
"text": "$_id.B",
"details": "$_id.C",
"leaf": {'$literal': true},
}
},
}}
])
I would like to add in my json output some hardcoded properties and values, it works with
"leaf": {'$literal': true}
but I don't know why I can't make it with
"allowDrag": {'$literal':false}, "expanded": {'$literal':false}
is it possible with $group?
Example of the output json I've got :
"result" : [
{
"_id" : "A",
"cpt" : 1,
"children" : [
{
"text" : "B",
"details" : "C",
"leaf" : true
}
]
}]
Example of the output json I wish I had :
"result" : [
{
"_id" : "A",
"cpt" : 1,
"allowDrag" : false,
"expanded" : false,
"children" : [
{
"text" : "B",
"details" : "C",
"leaf" : true
}
]
}]
Upvotes: 2
Views: 230
Reputation: 103365
Use the $literal
operator in the $project
pipeline to return the new fields set to boolean values of false:
db.mydb.aggregate([
{
"$group": {
"_id": {
"A": "$A",
"B": "$B",
"C": "$C"
}
}
},
{
"$group": {
"cpt": { '$sum': 1 } ,
"_id": "$_id.A",
"children": {
"$push": {
"text": "$_id.B",
"details": "$_id.C",
"leaf": {'$literal': true}
}
}
}
},
{
"$project": {
"allowDrag": {'$literal':false},
"expanded": {'$literal':false},
"cpt": 1,
"children": 1
}
}
])
Tested with the following collection sample:
db.mydb.insert([
{
"A": "test1",
"B": "test2",
"C": "test3"
},
{
"A": "test1",
"B": "test2",
"C": "test2"
},
{
"A": "test2",
"B": "test2",
"C": "test3"
},
{
"A": "test2",
"B": "test2",
"C": "test3"
}
])
The above aggregation gives the following results:
/* 0 */
{
"result" : [
{
"_id" : "test1",
"cpt" : 2,
"children" : [
{
"text" : "test2",
"details" : "test2",
"leaf" : true
},
{
"text" : "test2",
"details" : "test3",
"leaf" : true
}
],
"allowDrag" : false,
"expanded" : false
},
{
"_id" : "test2",
"cpt" : 1,
"children" : [
{
"text" : "test2",
"details" : "test3",
"leaf" : true
}
],
"allowDrag" : false,
"expanded" : false
}
],
"ok" : 1
}
Upvotes: 2