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

huangapple go评论70阅读模式
英文:

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?

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

答案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}}}

huangapple
  • 本文由 发表于 2021年10月10日 02:36:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/69509588.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定