为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
哔哔one 2023-08-07 15:09:00
我正在使用"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
查看完整描述

1 回答

?
慕沐林林

TA贡献2016条经验 获得超9个赞

您无法“禁用”地图中的字段,但可以$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},

}


查看完整回答
反对 回复 2023-08-07
  • 1 回答
  • 0 关注
  • 78 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信