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 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题