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

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

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:

  1. {
  2. "_id",
  3. "numbers" : {
  4. "fst",
  5. "snd",
  6. "thd"
  7. },
  8. "none" : [
  9. {
  10. "fst",
  11. "snd",
  12. "thd",
  13. "email"
  14. }
  15. ],
  16. "twoNums" : [
  17. {
  18. "fst",
  19. "snd",
  20. "thd",
  21. "email"
  22. }
  23. ],
  24. "threeNums" : [
  25. {
  26. "fst",
  27. "snd",
  28. "thd",
  29. "email"
  30. }
  31. ]
  32. }

I tried:

  1. 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"

  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

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

答案1

得分: 5

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

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

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

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

答案2

得分: 0

使用以下代码:

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

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

英文:

use

  1. 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:

确定