mongodb - 在 mongodb 中找到数组的最后一个索引

标签 mongodb go mgo

在后端我使用 go lang,数据库我使用 mongoDB。我试图找到嵌入数组中插入的最后一个文档,这样我就可以在不知道其索引的情况下检索最后一个数组索引中的文档。现在我正在获取员工的所有文档,然后找到最后一个索引。这就像重载我的 RAM 因为我需要检索 1000 条员工记录并将其存储在 ram 中,然后再找到数组的最后一个索引 我的结构如下

 type (
        Employee struct {
            Name               string
            Password           string
            EmpId              string 
           EmailAddress       string
           Position           string
           Gender             string
           Nationality        string
           Department         string
           MaritalStatus      string
           Approvedby         string
           JoinDate           time.Time
           ConfirmationDate   time.Time
           EndDate            time.Time
            Leave             []*LeaveInfo  
        }
        LeaveInfo struct {
            Total        float64
            Id           int
            Days         float64
            From        time.Time
             To          time.Time  
            Status       string
            Certificate  []*CertificateInfo
        }
        CertificateInfo struct {
            FileName string
            FileType string
            FileSize int

        }

这是我在申请中的做法

 My code is follows

    employee := Employee{}
    err = c.Find(bson.M{
                  "empid": "1234"
                 }).One(&result)
    if err != nil {
            log.Fatal(err)
    }
          name:=result.Name        
          lastindex:= result.LeaveInfo[len(result.LeaveInfo)-1].Id

如您所见,我检索了整个员工数据,然后找到了最后一个文档的 ID。有没有更好的方法来执行此操作。感谢任何帮助。请...谢谢...

Newly Added Codes

 This code is based on your example

   var result bson.M

    query := bson.M{"empid": "1234"}  // gets the employee you are interested in
    match := bson.M{"$match": query}  // Set up the match part of the pipeline
    unwind := bson.M{"$unwind": "$leave"}  // sets up the leave field to be unwound

    pipeline := []bson.M{match, unwind,{
    "$project":bson.M{
           "ID":bson.M{
                "$slice": []interface{}{"$leave.id", -1},
        }
       }


    iter := postCollection.Pipe(pipeline).Iter()
    for iter.Next(&result) {
        fmt.Printf("%+v\n", result)
    }
    iter.Close()

这段代码给了我很多相同的文档,比如 542 个文档。但是所有这些文档都是相同的...

最佳答案

如果您在 Mongo 上运行一个包含 $slice 的版本,它是在 2.4 中引入的,您可以在 Find 中使用它并添加一个 Select 函数,它的工作方式类似于项目。

err = c.Find(bson.M{"empid": "1234"}).Select(bson.M{"name": 1, "leave": bson.M{"$slice": -1}}).One(&result) // result is an Employee struct

否则,聚合就是你的 friend 。您需要使用管道并展开 Employee Leave 字段。

有几个简单的步骤:

1) 根据您的员工记录定义一个结果记录,其中 Leave 字段定义为单个 LeaveInfo 而不是 LeaveInfo 的一部分,例如

EmployeeResult struct {
    Name   string    `bson:"name"`
    Leave  LeaveInfo `bson:"leave"`
}

不要忘记使 bson 标签与 Employee 结构中的 LeaveInfo 标签同名。

2) 然后创建一个包含几个阶段的管道:

query := bson.M{"empid": "1234"}  // gets the employee you are interested in
match := bson.M{"$match": query}  // Set up the match part of the pipeline
unwind := bson.M{"$unwind": "$leave"}  // sets up the leave field to be unwound
pipeline := []bson.M{match, unwind} // the pipeline you are passing to pipe. I like to split the parts of the pipe call up for clarity and ease of later modification

3) 使用管道作为参数调用 Pipe,然后迭代结果,这应该一次给你一个 LeaveInfo

var (
    result EmployeeResult
)
iter := postCollection.Pipe(pipeline).Iter()
for iter.Next(&result) {
    fmt.Printf("%+v\n", result)
}
iter.Close()

4) 在循环结束时,结果将是列表中的最后一项,或者如果没有读取任何内容则为空白。

关于mongodb - 在 mongodb 中找到数组的最后一个索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40544700/

相关文章:

node.js - 查询 Mongoose 中的所有数组匹配项

node.js - 如何在 Mean Stack (Node.js + Mongodb) 上的用户身份验证中检查当前登录的用户?

oop - 如何实现功能共享相同逻辑的接口(interface)?

go - 使用Go将struct have数组插入Mongodb

mongodb - mgo time.Time 或 bool 检查

mongodb - 模型结构中的嵌套文档

javascript - 项目数组的同步插入或增量

javascript - 如何根据 mongodb/mongoose 查询中的参数更改结果位置?

go - 使用go例程初始化多个服务

go - HMGET : Empty result when passing params