Anton Krivokhizhin
Anton Krivokhizhin

Reputation: 35

Golang and Mgo sort by $natural: -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)

Upvotes: 1

Views: 6608

Answers (2)

RickyA
RickyA

Reputation: 16029

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)

Upvotes: 5

simon_xia
simon_xia

Reputation: 2544

use

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

Upvotes: 0

Related Questions