问题如何在Golang中将mongodb的命令转换为Bson
Question how to convert mongodb's commands to Bson in Golang
这是collection列表
{
_id : autoIncrement
"P_NAME" : "Name",
"P_LIST" : [
{
_id : autoIncrement
"P_TYPE" : "HELL",
"P_POOL" : "Not Use"
}
]
}
我在MongoDB.
中用过这个命令
db.P.find({},{"P_LIST": {$elemMatch: {_id:2}}, _id: 0})
同样在Golang中,我试图搜索这样的条件,但没有成功。
collection.Find(context.TODO(), bson.M{bson.M{}, bson.M{"P_LIST":bson.M{"$elemMatch":bson.M{"_id":2}}, bson.M{"_id": 0}}})
Golang 如何使用带有条件和过滤器的 Find 命令,例如 MongoDB?
你调用 Find
错误,你将过滤器和投影传递到 Find 的过滤器参数中。
func (coll *Collection) Find(ctx context.Context, filter interface{},
opts ...*options.FindOptions) (*Cursor, error)
尝试这样做:
collection.Find(
context.TODO(),
nil,
options.Find().SetProjection(bson.M{
"P_LIST": bson.M{
"$elemMatch": bson.M{"_id": 2},
"_id": 0,
},
})
)
查看有关 Find
here
的更多详细信息
这是collection列表
{
_id : autoIncrement
"P_NAME" : "Name",
"P_LIST" : [
{
_id : autoIncrement
"P_TYPE" : "HELL",
"P_POOL" : "Not Use"
}
]
}
我在MongoDB.
中用过这个命令db.P.find({},{"P_LIST": {$elemMatch: {_id:2}}, _id: 0})
同样在Golang中,我试图搜索这样的条件,但没有成功。
collection.Find(context.TODO(), bson.M{bson.M{}, bson.M{"P_LIST":bson.M{"$elemMatch":bson.M{"_id":2}}, bson.M{"_id": 0}}})
Golang 如何使用带有条件和过滤器的 Find 命令,例如 MongoDB?
你调用 Find
错误,你将过滤器和投影传递到 Find 的过滤器参数中。
func (coll *Collection) Find(ctx context.Context, filter interface{},
opts ...*options.FindOptions) (*Cursor, error)
尝试这样做:
collection.Find(
context.TODO(),
nil,
options.Find().SetProjection(bson.M{
"P_LIST": bson.M{
"$elemMatch": bson.M{"_id": 2},
"_id": 0,
},
})
)
查看有关 Find
here