I set up my facet
like that:
metadataStage := bson.D{
{"$facet", bson.D{
{"metadata", bson.A{bson.D{
{"$group", bson.D{
{"_id", nil},
{"total", bson.D{{"$sum", 1}}}}}}, // get number of documents that matches the all above conditions
}},
{"data", bson.A{bson.D{
//{"$sort", sortStage}, // sort by field and direction
{"$skip", skip}, // skip number of documents
{"$limit", limit}}}}, // limit them
}},
}
but when I run my code, Mongo Driver always alerts the error A pipeline stage specification object must contain exactly one field.
. I do not think that this is a syntax error. Please help me, thank you so much
CodePudding user response:
Each pipeline for the data facet should be element of an array
metadataStage := bson.D{
{"$facet", bson.D{
{"metadata", bson.A{
bson.D{{"$group", bson.D{
{"_id", nil},
{"total", bson.D{{"$sum", 1}}}}}}, // get number of documents that matches the all above conditions
}},
{"data", bson.A{
//bson.D{{"$sort", sortStage}}, // sort by field and direction
bson.D{{"$skip", skip}}, // skip number of documents
bson.D{{"$limit", limit}}}}}, // limit them
}}
Alternately, you could write to be clear that you are declaring stages of the pipeline for the facets.
metadataStage := bson.D{
{"$facet", bson.D{
{"metadata", mongo.Pipeline{
bson.D{{"$group", bson.D{
{"_id", nil},
{"total", bson.D{{"$sum", 1}}}}}}, // get number of documents that matches the all above conditions
}},
{"data", mongo.Pipeline{
//bson.D{{"$sort", sortStage}}, // sort by field and direction
bson.D{{"$skip", skip}}, // skip number of documents
bson.D{{"$limit", limit}}}}}, // limit them
}}