【问题标题】:Disable certain field in Go mongo bson map禁用 Go mongo bson 地图中的某些字段
【发布时间】:2020-03-24 06:20:54
【问题描述】:

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

这个sn-p肯定不会编译Missing key in map literal

【问题讨论】:

    标签: mongodb dictionary go bson mongo-go


    【解决方案1】:

    您不能“禁用”地图中的字段,但可以有条件地构建 $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},
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-14
      • 1970-01-01
      • 2015-03-15
      • 2017-09-15
      • 1970-01-01
      相关资源
      最近更新 更多