禁用Go mongo bson地图中的某些字段

问题描述 投票:1回答:1

我正在使用"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

mongodb dictionary go bson mongo-go
1个回答
0
投票

您无法“禁用”地图中的字段,但可以有条件地构建$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},
}
© www.soinside.com 2019 - 2024. All rights reserved.