在 Go mongo bson 映射中禁用某些字段

Disable certain field in Go mongo bson map

我正在使用 "go.mongodb.org/mongo-driver/bson"
有没有办法能够禁用一个字段,但仍然是一个有效的 bson 映射?

publishFilter := bson.M{}

if publishedOnly {
    publishFilter = bson.M{"published": true}
}

pipeline := []bson.M{
    {"$sort": bson.M{"_id": -1}},
    {
        "$match": bson.M{
            "_id": bson.M{
                "$gt":  sinceObjectID,
                "$lte": maxObjectID,
            },
            publishFilter, // I want to control this to be nothing or `{"published": true}`
            // depending on `publishedOnly`
        },
    },
    {"$limit": query.Count},
}

这段代码肯定编译不了Missing key in map literal

您不能 "disable" 地图中的字段,但您可以有条件地构建 $match 文档:

matchDoc := bson.M{
    "_id": bson.M{
        "$gt":  sinceObjectID,
        "$lte": maxObjectID,
    },
}

if publishedOnly {
    matchDoc["published"] = true
}

pipeline := []bson.M{
    {"$sort": bson.M{"_id": -1}},
    {"$match": matchDoc},
    {"$limit": query.Count},
}