我用的是"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
发布于 2019-11-28 14:57:56
不能“禁用”映射中的字段,但可以有条件地构建$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},
}https://stackoverflow.com/questions/59091460
复制相似问题