arrays - Golang 在 json 响应中获取数组索引值

标签 arrays json mongodb sorting go

所以我对数据库 (mongodb) 有一些查询,它将按值字段对结果进行排序。

all := EValues{}
err := con.Find(bson.M{"name": "somename}).Sort("-value").All(&all)

Json 输出如下:

 "values": [
    {
      "user_name": "guest7485",
      "value": 8911,
      "value_date": "2016-03-09T14:40:34.512Z"
    },
    {
      "user_name": "guest7485",
      "value": 539,
      "value_date": "2016-03-07T14:11:05.217Z"
    },
    {
      "user_name": "guest7485",
      "value": 221,
      "value_date": "2016-03-07T14:11:08.853Z"
    },
    {
      "user_name": "guest7485",
      "value": 77,
      "value_date": "2016-03-07T14:11:12.377Z"
    }
  ]

在我的 json 响应中,我需要为所有结果添加参数“position”,它应该基本上等于 1 - 第一个结果,2 - 第二个结果等等。所以我的最终输出应该是:

 "values": [
    {
      "position": 1,
      "user_name": "guest7485",
      "value": 8911,
      "value_date": "2016-03-09T14:40:34.512Z"
    },
    {
      "position": 2,
      "user_name": "guest7485",
      "value": 539,
      "value_date": "2016-03-07T14:11:05.217Z"
    },
    {
      "position": 3,
      "user_name": "guest7485",
      "value": 221,
      "value_date": "2016-03-07T14:11:08.853Z"
    },
    {
      "position": 4,
      "user_name": "guest7485",
      "value": 77,
      "value_date": "2016-03-07T14:11:12.377Z"
    }
  ]

我想知道如何用 mgo 和 go 解决这个问题,如果有人能给我最有效的方法来解决这个问题,我会非常高兴。

更新:

Evalues 的定义如下:

type EValue struct {
    ID bson.ObjectId `json:"-" bson:"_id,omitempty"`
    Name string             `json:"-" bson:"name"`
    UserId    bson.ObjectId `json:"-" bson:"userId"`
    UserName  string        `json:"user_name" bson:"userName"`
    Value     int64         `json:"value" bson:"value"`
    AddedTime time.Time     `json:"value_date" bson:"addedTime"`
}

type EValues []EValue

最佳答案

向 EValue 添加一个位置字段:

type EValue struct {
    ... other fields here
    Position int `json:"position" bson:"-"`
}

遍历数据库结果并设置字段:

for i := range all {
    all[i].Position = i + 1
}

将结果编码为 JSON。

关于arrays - Golang 在 json 响应中获取数组索引值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35919380/

相关文章:

php - 如何在 While 循环中初始化关联数组?

javascript - 如何使用 Javascript 中的动态链接数组发出多个 Axios 请求?

mongodb - 使用 Mongoose 和 SRV 连接字符串将数据插入 MongoDB Atlas

php - 通知 : Array to string conversion in

javascript - 如何使用 lodash 从复杂的对象数组中获取值?

python - 从 Python 创建 JSON 的更有效方法

java - Jersey 将空值序列化为 json : How to skip

javascript - 将javascript对象转换为有序的逗号分隔值

c++ - mongo upsert 性能 (C++)

python - mongoDB:PyMongo 中包含单个字母的字符串的全文查询