How to use $arrayElemAt with MongoDb

Issue

I have the following pipeline, which I want to use it in Golang and convert it to bson.M. One way is using bson.UnmarshalExtJSON but I want to know what is exact equivalent of bson.M of this pipeline. In fact my problem is in $arrayElemAt line.

            "$lookup": {
                        "from" : "cities",
                        "localField": "cityId",
                        "foreignField": "_id",
                        "as" : "city"
                    }}
            , {
            "$project": {
              "_id": 0,
              "name": 1,
              "age": 1,
              "city": { "$arrayElemAt" : ["$city.name", 0]}
            }}

I use this bson.M:

   stage1 := bson.M{
        "$lookup": bson.M{
            "from": "cities",
            "localField": "cityId",
            "foreignField": "_id",
            "as" : "city",
        },
    }

    stage2 := bson.M{
        "$project": bson.M{
            "_id": 0,
            "name": 1,
            "age": 1,
            "city": bson.M{ "$arrayElemAt" : bson.M{"$city.name", 0} },
        },
    }

    pipeline := make([]bson.M, 0)

    pipeline = append(pipeline, stage1)
    pipeline = append(pipeline, stage2)

The above code gives me compiler error: missing key in map literal at the line I have “city”: bson.M{ “$arrayElemAt” : bson.M{“$city.name”, 0} }. So what is the correct way of defining $arrayElemAt as bson.M?

Solution

The correct way to translate

"city": { "$arrayElemAt" : ["$city.name", 0]}

would be:

bson.M{"$arrayElemAt":[]interface{}{"$city.name",0}

You were getting the compile error because of this:

bson.M{"$city.name", 0} 

bson.M is a map, thus the correct syntax should use a : instead of a ,.

Answered By – Burak Serdar

Answer Checked By – Marie Seifert (GoLangFix Admin)

Leave a Reply

Your email address will not be published.