'How to use $arrayElemAt with MongoDb

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 1:[1]

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 ,.

Solution 2:[2]

Maybe use below syntax work for you where bson.A for array:

bson.M{ "$arrayElemAt": bson.A{"$city.name", 0}}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Manish Sharma