Home  >  Article  >  Backend Development  >  Filter query mongodb Golang

Filter query mongodb Golang

WBOY
WBOYforward
2024-02-12 08:33:18736browse

过滤查询 mongodb Golang

php editor Xigua today will introduce to you the Golang implementation of filtering query mongodb. When using mongodb database for data query, we often need to filter the query results to meet specific conditions. As a powerful programming language, Golang provides a rich mongodb driver library, which can easily implement filtering query functions. Next, we will introduce in detail how to use mongodb to filter queries in Golang to help everyone better apply and understand this function.

Question content

I'm trying to get a list of data that matches a specific query but I'm getting this error

"(atlaserror) merchant is not allowed or the syntax is incorrect, see
the atlas documentation for more information"
func ...

var result []*model.Package

    ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
    defer cancel()

    tokenData, err := middleware.CtxValue(ctx)

    if err != nil {
        return nil, err
    }

    orQuery := []bson.M{}
    merchant := "abc"
    completedQuery := bson.M{"status": "completed"}
    cancelledQuery := bson.M{"status": "cancelled"}
    orQuery = append(
        orQuery,
        cancelledQuery,
        completedQuery)
    limit64 := int64(limit)
    page64 := int64(page)
    match := bson.M{"$match": bson.M{"$nor": orQuery}}
    var filterQuery primitive.M

    if tokenData.Role == "admin" && merchant != nil {
        filterQuery = bson.M{"merchant": bson.M{"id": merchant}}
    } else {
        filterQuery = bson.M{"user": bson.M{"id": tokenData.Id}}
    }
    paginatedData, err1 := paginate.New(r.Collection).Context(ctx).Limit(limit64).Page(page64).Aggregate(match, filterQuery)
    if err1 != nil {
        return nil, err1
    }


...

Solution

filterquery, seems to contain { "merchant" : { "id" : "abc" } }, which is passed alone Give .aggregate(). But the aggregation framework expects to receive something that represents a series of pipeline stages. Each phase is outlined in the documentation and is expected to start with $ characters, e.g. $match phase.

The current database is trying to handle merchant as the options of the pipeline (see here and here). But such option does not exist, hence the error message.

To fix this, you should merge the filterquery logic into the existing match variables/stages you are building and passing. Alternatively, you can wrap filterquery in different $match and pass them (as a single argument) to .aggregate().

This example 文档中的a> shows them building multiple stages and then submitting them together via mongo.pipeline{...}:

.aggregate()
// create the stages
matchStage := bson.D{{"$match", bson.D{{"toppings", "milk foam"}}}}
unsetStage := bson.D{{"$unset", bson.A{"_id", "category"}}}
sortStage := bson.D{{"$sort", bson.D{
    {"price", 1},
    {"toppings", 1}},
}}
limitStage := bson.D{{"$limit", 2}}

// pass the stage into a pipeline
// pass the pipeline as the second paramter in the Aggregate() method
cursor, err := coll.Aggregate(context.TODO(), mongo.Pipeline{matchStage, unsetStage, sortStage, limitStage})

The above is the detailed content of Filter query mongodb Golang. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete