SangGeol
SangGeol

Reputation: 65

Question how to convert mongodb's commands to Bson in Golang

This is collection list

{
    _id : autoIncrement
    "P_NAME" : "Name",
    "P_LIST" : [
        {
            _id : autoIncrement
            "P_TYPE" : "HELL",
            "P_POOL" : "Not Use"
        }
    ]
}

I used this command when I used it in MongoDB.

db.P.find({},{"P_LIST": {$elemMatch: {_id:2}}, _id: 0})

And similarly in Golang, I tried to search for such a condition, but it did not work.

collection.Find(context.TODO(), bson.M{bson.M{}, bson.M{"P_LIST":bson.M{"$elemMatch":bson.M{"_id":2}}, bson.M{"_id": 0}}})

How can Golang use the Find command with conditions and filters like MongoDB?

Upvotes: 1

Views: 557

Answers (1)

Ayoub
Ayoub

Reputation: 1435

You're calling Find wrong, you pass the filter and projection into Find's filter param.

func (coll *Collection) Find(ctx context.Context, filter interface{},
    opts ...*options.FindOptions) (*Cursor, error)

Try doing it like this:

collection.Find(
    context.TODO(),
    nil,
    options.Find().SetProjection(bson.M{
        "P_LIST": bson.M{
            "$elemMatch": bson.M{"_id": 2},
            "_id":        0,
        },
    })
)

See more details about Find here

Upvotes: 1

Related Questions