Using Aggregate Pipeline Stages With Mongodb Golang
As you already know how to connect with mongodb in previous post, today i will tell about aggregate pipeline in mongodb. it is like you are adding bunch of filters to your mongodb query.
In aggregate pipeline there are many stages, each stage have its own filter query.
for example suppose you have to filter users based on email and also you have to limit the record as well as you have to sort the output and also you have to modify the output based on some projection then all those you can do in stages.
for ex:
// this is for matching element
matchCondition := bson.D{{"email","abc@example.com"}}
// this is for offset if you are trying to paginate the results
offsetStage := bson.D{
bson.E{ Key : "$skip", Value: 1} // 1 is offset number
}
// limiting the number of records
limitStage := bson.D(
bson.E{
Key: "$limit", Value: 10 // 10 will be the number of records
}
)
// projection stage if you want ot modify the response object
projectStage := bson.D{{"$project", bson.D{{"title", 1}, {"course_id", 1}}}}
// combining all stages
pipelineStages := bson.A{
matchCondition,
offsetStage,
limitStage,
projectStage,
}
// now apply all the stages to collection using aggregate pipeline
cursor, err := collection.Aggregate(context.Todo(),pipelineStages)
i will create a new post for complete working example in few days. you can get idea how you can use multiple stages from this post.
Stay tuned for more post.