Golang and Mgo sort by $natural: -1

6.5k views Asked by At

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)
2

There are 2 answers

1
RickyA On BEST ANSWER

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)
3
simon_xia On

use

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