在 Golang 中使用 mgo 包无法获取 mongodb 中对象的 "_id" 字段
大家讲道理
大家讲道理 2017-04-22 08:59:42
[MongoDB讨论组]

这是我的结构体:

type Article struct {
    Id      bson.ObjectId `json:"id"        bson:"_id"`
    Title   string        `json:"title"`
    Author  string        `json:"author"`
    Date    string        `json:"date"`
    Tags    string        `json:"tags"`
    Content string        `json:"content"`
    Status  string        `json:"status"`
}

这是我获取 mongodb 中数据的函数:

func AllArticles() []Article {
    articles := []Article{}
    err := c_articles.Find(bson.M{}).All(&articles)
    if err != nil {
        panic(err)
    }
    fmt.Println(articles)
    return articles
}

这是打印结果:

[{ObjectIdHex("") Hello1 DYZ 2013-11-10 abc This is another content. published} {ObjectIdHex("") Hello2 DYZ 2013-11-14 abc This is the content. published} {ObjectIdHex("") Hello3 DYZ 2013-11-15 abc This is the content haven't been published. draft}]

可以看到,对应_id的值是ObjectIdHex(""),但是在数据库中的数据是这样的:

{ "_id" : ObjectId("5281b83afbb7f35cb62d0834"), "title" : "Hello1", "author" : "DYZ", "date" : "2013-11-10", "tags" : "abc", "content" : "This is another content.", "status" : "published" }

即使我把筛选条件变成:

err := c_articles.Find(bson.M{"_id": bson.ObjectIdHex("5281b83afbb7f35cb62d0834")}).All(&articles)

打印出来的数据仍然是上面那样,没有值。这是为什么?

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

全部回复(1)
黄舟

Id bson.ObjectId json:"id" bson:"_id"

json和bson之间的空格是否用了tab?

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号