我正在嘗試使用 Go 查找嵌套文檔中是否存在字段。目前,該文檔如下所示。我正在嘗試查看該用戶的購物車中是否存在項目 ID 字段 - 5f15d53f205c36fa8b022089。使用 Mongo Compass,我能夠使用此過濾器命令成功查詢正確的文檔。{"_id": ObjectId('5f19a8950268ef67ce0c5124'), "shoppingCart.items.5f15d53f205c36fa8b022089": {$exists: true}} 我嘗試在 Go 中使用相同的語法,但我仍然沒有從結果中得到任何回報。cursor, err := customersCollection.Find( ctx, bson.M{"_id": customerID, "shoppingCart.items.5f15d53f205c36fa8b022089": bson.M{"$exists": true}}, options.Find().SetProjection(bson.M{"_id": 1}), ) // This is how I am reading the results from the cursor. When // printing the results, I get an empty array. var results []bson.M if err = cursor.All(ctx, &results); err != nil { customerLog.Errorf(logger.LogError(logger.LogInfo()), err) } fmt.Printf("Products Result: %v\n", results)我找不到任何有關在過濾器參數中包含元素查詢運算符的正確方法的文檔。這是我正在使用的 Mongo 驅動程序,https://godoc.org/go.mongodb.org/mongo-driver/mongo編輯 1.0 我嘗試過的事情:使用 bson.D 而不是 bson.M。更新了代碼段。光標,錯誤:=customersCollection.Find(ctx,bson.D{{“_id”,customerID},{“shoppingCart.items.5f15d53f205c36fa8b022089”,bson.D{{“$exists”,true}}}},選項。 Find().SetProjection(bson.M{"_id": 1}), )
2 回答

莫回無
TA貢獻1865條經驗 獲得超7個贊
如果您使用go.mongodb.org/mongo-driver/bson包,您可以執行以下操作:
query := bson.M{}
query["_id"] = bson.M{
"$exists": true,
}
如果你愿意,你也可以通過使用包裝器來做更清潔:
type FilterQuery bson.M
func NewFilterQuery() FilterQuery {
return FilterQuery(bson.M{})
}
func (q FilterQuery) SetIdExists(exist bool) FilterQuery {
q["_id"] = bson.M{
"$exists": exist,
}
return q
}
然后從您的代碼中,您可以執行類似的操作
query := NewFilterQuery()
query.SetIdExist(true)
..
cursor, err := customersCollection.Find(
ctx,
query,
)
...
- 2 回答
- 0 關注
- 126 瀏覽
添加回答
舉報
0/150
提交
取消