关于如何在Golang中将mongodb的命令转换为Bson的问题

问题描述 投票:1回答:1

这是收藏列表

{
    _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如何在条件和过滤器(如MongoDB)中使用Find命令?

json mongodb go mongodb-query bson
1个回答
1
投票

您输入错误的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的更多详细信息>

© www.soinside.com 2019 - 2024. All rights reserved.