我正在使用"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},
}
- 1 回答
- 0 關注
- 143 瀏覽
添加回答
舉報
0/150
提交
取消