Home > Software engineering >  How to concatenate two fields in go with mongodb when using GET method?
How to concatenate two fields in go with mongodb when using GET method?

Time:11-15

I have a model is like this

type Employee struct {
    LastName   string    `bson:"lastName"`
    FirstName  string    `bson:"firstName"`
}

whenever I want to get all employees, I want my json to be like this:

{
  "firstName": "Dan",
  "lastName": "Tom",
  "name":     "Tom Dan"
}

CodePudding user response:

Try the aggregate function from the collection

func GetAllEmployees() ([]*primitive.M, error) {

    var employees []*bson.M
    var err error

    findOption := []bson.M{
        {"$project": bson.M{
            "id": "$_id",
            "name": bson.M{
                "$concat": []string{
                    "$lastName", " ", "$firstName",
                },
            },
            "lastName":   "$lastName",
            "firstName":  "$firstName",
        }}}

    cur, err := employeesCollection.Aggregate(ctx, findOption)
    if err != nil {
        // log.Fatal(err)
        return nil, err
    }

    if err = cur.All(ctx, &employees); err != nil {
        // log.Fatal(err.Error())
        return nil, err
    }

    return employees, err

}
  • Related