英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论