duanliang9288 2016-04-05 19:45 采纳率: 100%
浏览 347
已采纳

根据Go子文档中的字段对mongodb查询进行排序

suppose I have the following struct

type Test struct {
  Title  string `bson:"title" json:"title"`
  Update Update `bson:"update" json:"update"`
}

type Update struct {
  Changes    []string  `bson:"change" json:"change"`
  UpdatedAt time.Time `bson:"updatedAt" json:"updatedAt"`
}

And suppose I want to sort my results in the Query by "update.updatedAt"

cs.Find(bson.M{title: "some title"}).Sort("-update.updatedAt").Limit(10).All(&results)

This query does not work as expected. I can't seem to find any documentation about how to sort a Query by a subdocument field. Intuitively, I was certain that my example would work. For reference, "-updatedAt" works just fine, but for reasons that aren't necessary to explain, I have to keep Update as a subdocument of Test.

Every example and Stack Overflow question I have seen so far involves the sorting and reordering of subdocuments, or arrays. In this case I don't care about the order of my subdocuments, and I'm not sorting by anything inside of an array. I merely want to sort my the documents by the date of a subdocument.

Is there a way to do this with the Go Mgo Query library?

  • 写回答

2条回答 默认 最新

  • douju1365 2016-04-06 00:50
    关注

    I'm pretty sure it is something with your data structures because next code works as expected (you can test it on your PC)

    package main
    
    import (
        "fmt"
        "gopkg.in/mgo.v2"
        "gopkg.in/mgo.v2/bson"
        "log"
        "time"
    )
    
    type Test struct {
        Title  string `bson:"title" json:"title"`
        Update Update `bson:"update" json:"update"`
    }
    
    type Update struct {
        Changes   []string  `bson:"change" json:"change"`
        UpdatedAt time.Time `bson:"updatedAt" json:"updatedAt"`
    }
    
    func main() {
        session, err := mgo.Dial("mongodb://souser:123456@ds055855.mlab.com:55855/catalog")
    
        if err != nil {
            panic(err)
        }
        defer session.Close()
        session.SetMode(mgo.Monotonic, true)
    
        c := session.DB("catalog").C("sortable")
    
        /*
            // Fill collection with test data (test collection aready has 15 elements)
            for i := 0; i < 15; i++ {
                c.Insert(&Test{
                    Title: "Title",
                    Update: Update{
                        Changes:   []string{fmt.Sprintf("Changes #%d", i)},
                        UpdatedAt: time.Now(),
                    },
                })
            }
        */
    
        var results []Test
    
        err = c.Find(bson.M{"title": "Title"}).Sort("-update.updatedAt").Limit(10).All(&results)
        if err != nil {
            log.Fatal(err)
        }
    
        for _, e := range results {
            fmt.Println(e.Update.UpdatedAt)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料