如何追加到 bson 对象

rad*_*ive 1 go mongodb

我有一个端点,用户可以使用查询参数过滤 mongo 集合。如果我只有一个查询参数,例如title,我可以这样做 -

filter := bson.M{}

if params.Title != "" {
    filter = bson.M{"title": params.Title}
}
Run Code Online (Sandbox Code Playgroud)

但是,如果我有多个查询参数,我似乎无法了解如何附加到对象bson

我尝试过这个 -

filter := []bson.M{}

if params.Title != "" {
    filter = append(filter, bson.M{"title": params.Title})
}

if params.Description != "" {
    filter = append(filter, bson.M{"description": params.Description})
}
Run Code Online (Sandbox Code Playgroud)

但我收到了这个错误 -cannot transform type []primitive.M to a BSON Document: WriteArray can only write a Array while positioned on a Element or Value but is positioned on a TopLevel

我该如何解决这个问题?

nip*_*una 7

bson.M{}map[string]interface{}go-mongo-driver中带有下划线。所以如果你需要添加更多的elemnet,你可以不追加。只需将该值分配给地图的键,如下所示。

    filter := bson.M{}
    
    if params.Title != "" {
        //filter = bson.M{"title": params.Title}
        filter["title"] = params.Title
    }

    if params.Description != "" {
        filter["description"] =  params.Description
    }
Run Code Online (Sandbox Code Playgroud)