我正在使用MongoDb Go 驱动程序 https://github.com/mongodb/mongo-go-drive我无法从结构中解码的 JSON 中获取 ObjectId 子值。
Note:我使用的库/API 与这个问题 https://stackoverflow.com/questions/47712710/cant-get-mongodb-record-by-objectid-in-golang,所以请不要将其标记为重复。
import (
"net/http"
"github.com/go-chi/chi"
"encoding/json"
"time"
"context"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"fmt"
)
我有一种像这样的结构来处理结果
type Contact struct {
Id struct {
ObjId string `json:"$oid"`
} `json:"_id"`
Name string `json:"name"`
Email string `json:"email"`
Health struct {
Weight int `json:"weight"`
Height int `json:"height"`
} `json:"health"`
}
然后我像这样检索联系人:
var contacts []Contact
ctx, _ := context.WithTimeout(context.Background(), 30*time.Second)
cursor, err := collection.Find(ctx, bson.M{})
if err != nil {
panic(err)
}
defer cursor.Close(ctx)
for cursor.Next(ctx) {
var contact Contact
fmt.Println(cursor)
cursor.Decode(&contact)
contacts = append(contacts, contact)
}
if err := cursor.Err(); err != nil {
panic(err)
}
// I want to do more with the contacts, but .Id is empty :-(
fmt.Println(contacts)
子字段为"health"
完全按照应有的方式显示,但由于某种原因,子字段来自"_id"
部分结果无处可寻。谁能帮我这个??
来自数据库的 JSON 响应如下所示,由于某种原因,我能够获取health
场,但不是_id
场地。为什么不?
数据库的原始 JSON 响应
[{
"_id": {
"$obj": "5c601648ae25e40e2631c3ef"
},
"name": "Bob Smith",
"email": "[email protected] /cdn-cgi/l/email-protection",
"health": {
"height": 192,
"weight": 85
}
}]
fmt.Println
解码后的输出contacts
大批:
[{{} Bob Smith [email protected] /cdn-cgi/l/email-protection {192 85}}]