我正在尝试使用 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 关注
- 132 浏览
添加回答
举报
0/150
提交
取消