我正在使用“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},
}
此代码段绝对无法编译 map 文字中缺少键
最佳答案
您无法“禁用” map 中的字段,但您可以有条件地构建 $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},
}
关于mongodb - 禁用 Go mongo bson map 中的某些字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59091460/