MongoDB 通过 Go 在对象数据中返回键值对数组
时间:2024-02-20
浏览:374
作者:佚名
本篇文章向大家介绍《MongoDB 通过 Go 在对象数据中返回键值对数组》,主要包括,具有一定的参考价值,需要的朋友可以参考一下。
问题内容
我编写了以下查询,它返回使用golang中的mongodb库的所有记录中updated_at日期大于synced_at日期的记录。
pipeline := []bson.m{}
filter := []string{"$updated_at", "$synced_at"}
pipeline = append(pipeline, bson.m{"$match": bson.m{"$expr": bson.m{"$gte": filter}}})
opts := options.aggregate().setmaxtime(2 * time.second)
cursor, err := collection.aggregate(ctx, pipeline, opts)
for cursor.next(context.background()) {
records := model.ddata{}
err = cursor.decode(&records)
}
数据的结构是:
type ddata struct {
name string `json:"name" bson:"name"`
data interface{} `json:"data" bson:"data"`
updatedat time.time `json:"updated_at" bson:"updated_at"`
syncedat time.time `json:"synced_at" bson:"synced_at"`
}
集合中的数据采用以下形式:
{
"name":"vallabh",
"data":{
"field1":"value1",
"field2":"value2",
"field3":"value3",
},
"updated_at":2021-08-17t09:43:27z,
"synced_at":2021-08-07t09:43:27z
}
但是通过上面的查询,我得到的数据格式为:
{
"name":"Vallabh",
"data":[
{
"key":"field1",
"value":"value1"
},
{
"key":"field2",
"value":"value2"
},
{
"key":"field3",
"value":"value3"
}
}],
"updated_at":"2021-08-17T09:43:27Z",
"synced_at":"2021-08-07T09:43:27Z"
}
我做错了什么?仅当字段类型是结构体中的接口时才会发生。
正确答案
@vallabhlakade 我也有类似的担忧,并尝试了以下有帮助的方法。
基本上,问题在于,对于 interface{} 类型的结构, mongo-driver 默认解组为 bson.d ,而 mgo mgo-driver 默认为 bson.m 。
因此,我们必须在尝试与 mongo-db 建立连接时添加以下代码, setregistry() 选项为 clientopts 来映射旧的 mgo 行为,以便 mongo-driver 在取消映射时默认为 bson.m的结构输入 interface{} ,这不应将值显示为 key-value 对
tM := reflect.TypeOf(bson.M{})
reg := bson.NewRegistryBuilder().RegisterTypeMapEntry(bsontype.EmbeddedDocument, tM).Build()
clientOpts := options.Client().ApplyURI(SOMEURI).SetAuth(authVal).SetRegistry(reg)
client, err := mongo.Connect(ctx, clientOpts)
参考-> MongoDB document returns array of key value pair in go mongo-driver
到这里,我们也就讲完了《MongoDB 通过 Go 在对象数据中返回键值对数组》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.20
11.20
11.20
11.20
热门专题
