Golang和Mgo按$natural: -1进行排序。

huangapple go评论122阅读模式
英文:

Golang and Mgo sort by $natural: -1

问题

我只是尝试使用Golang和Mgo从我的MongoDB集合中获取最新的文档。

我的集合中的文档如下:

{
"_id",
"numbers": {
"fst",
"snd",
"thd"
},
"none": [
{
"fst",
"snd",
"thd",
"email"
}
],
"twoNums": [
{
"fst",
"snd",
"thd",
"email"
}
],
"threeNums": [
{
"fst",
"snd",
"thd",
"email"
}
]
}

我尝试了以下代码:

err := db.C("plays").Find(nil).Select(bson.M{"numbers": 1}).Sort("$natural:-1").Limit(1).One(&numbs)

并在"$natural"和"-1"之间加了一个空格:

err := db.C("plays").Find(nil).Select(bson.M{"numbers": 1}).Sort("$natural: -1").Limit(1).One(&numbs)

在MongoDB shell中,它运行得很完美:

db.getCollection('plays').find({}, {numbers: 1}).sort({$natural: -1}).limit(1)

英文:

I'm just trying to get the latest document in my collection in MongoDB with Golang and Mgo.

Document in my collection:

{
    "_id",
    "numbers" : {
        "fst",
        "snd",
        "thd"
    },
    "none" : [ 
        {
            "fst",
            "snd",
            "thd",
            "email"
        }
    ],
    "twoNums" : [ 
        {
            "fst",
            "snd",
            "thd",
            "email"
        }
    ],
    "threeNums" : [ 
        {
            "fst",
            "snd",
            "thd",
            "email"
        }
    ]
}

I tried:

err := db.C("plays").Find(nil).Select(bson.M{"numbers": 1}).Sort("$natural:-1").Limit(1).One(&numbs)

And with space between $natural and "-1"

err := db.C("plays").Find(nil).Select(bson.M{"numbers": 1}).Sort("$natural: -1").Limit(1).One(&numbs)

In MongoDB shell it works perfect

db.getCollection('plays').find({}, {numbers: 1}).sort({$natural: -1}).limit(1)

答案1

得分: 5

根据代码,我猜应该将-$natural用于逆向排序:

err := db.C("plays").
  Find(nil).
  Select(bson.M{"numbers": 1}).
  Sort("-$natural").
  Limit(1).
  One(&numbs)
英文:

Looking at the code I guess it should be -$natural for the reverse sort:

err := db.C("plays")
  .Find(nil)
  .Select(bson.M{"numbers": 1})
  .Sort("-$natural")
  .Limit(1)
  .One(&numbs)

答案2

得分: 0

使用以下代码:

db.C("plays").Find(nil).Select(bson.M{"numbers": 1}).Sort("$natural").Limit(1).One(&numbs)

请注意,这是一段Go语言的代码,用于在数据库中执行查询操作。

英文:

use

db.C("plays").Find(nil).Select(bson.M{"numbers": 1}).Sort("$-natural").Limit(1).One(&numbs)

huangapple
  • 本文由 发表于 2016年12月20日 17:30:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/41238921.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定