登录
首页 >  Golang >  Go问答

向MongoDB数组中添加对象

来源:stackoverflow

时间:2024-03-18 14:09:22 311浏览 收藏

在使用 MongoDB 时,向嵌套数组中添加对象时可能会遇到问题。本文介绍了一个示例,展示了如何使用 mongo-go-driver 向 student 结构的 users 数组中添加对象。然而,在提供的代码中,struct 元数据中用于标记数组的字段使用 json 标签,这可能会导致问题。本文建议将 json 标签更改为 bson 标签,以确保正确处理数组。

问题内容

type student struct {
    id           primitive.objectid   `bson:"_id,omitempty"`
    ...
    users      []primitive.objectid `json:"users"`
    ...
}

我有这个结构,我想添加到 users 数组 中。我正在这样做,并且正在使用 mongo-go-driver

// Filter for search
filter := bson.M{"_id": userID}

// Fields to update
update := bson.M{"$addToSet": bson.M{"users": ID}}

// Update the document
UsersCollection := GetUsersCollection()
UsersCollection.FindOneAndUpdate(context.Background(), filter, update, nil)

有人可以告诉我我做错了什么吗?它不会添加到数据库中,而是保持为空。


解决方案


更改建议:

  1. 将结构元数据标记 json 更改为 bson
type Student struct {
    ID           primitive.ObjectID   `bson:"_id,omitempty"`
    ...
    Users      []primitive.ObjectID   `bson:"users"`
    ...
}

到这里,我们也就讲完了《向MongoDB数组中添加对象》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>