英文:
Use $push operator on document with mongoDB GODriver without creating separate arrays
问题
我目前有一些GO代码,看起来像这样:
_, err = swapStruct.ReferenceCollection.UpdateByID(ctx, swapStruct.ReferenceID, bson.D{
{"$push", bson.D{{"students", objIDs}}},
})
要将一个对象ID数组插入到特定文档的"students"键下。然而,在该文档中,它最终被插入到"students.0"键下。我该如何将"objIDs"数组插入到该文档的"students"键下,而不是在"students"键下的"0"数组中?
英文:
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?
答案1
得分: 1
$push
将一个值推送到数组中。根据你的代码,你正在将一个数组作为单个元素进行推送。要推送数组的值,请使用$each
:
{"$push", bson.M{"students": bson.M{"$each": objIDs}}}
英文:
$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}}}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论