Search code examples
mongodbgomongo-go

Use $push operator on document with mongoDB GODriver without creating separate arrays


I currently have some GO code that looks like this:

   _, err = swapStruct.ReferenceCollection.UpdateByID(ctx, swapStruct.ReferenceID, bson.D{
        {"$push", bson.D{{"students", objIDs}}},
    })

to insert an array of objectIDs, to a specific document, under the "students" key. In that document though, it ends up being inserted under the "students.0" key. How do I insert the "objIDs" array into this document under the "students" key instead of it being under the "0" array under the student key?

enter image description here


Solution

  • $push pushes a value to an array. With your code, you are pushing an array as a single element. To push the values of an array, use $each:

    {"$push", bson.M{"students": bson.M{"$each": objIDs}}}