我正在尝试使用 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}), )
莫回无
aluckdog
相关分类