我正在为 MongoDB 开发一个 RESTful API 和 mgo 驱动程序。
问题是我试图通过 int 类型的字段获取文档,但没有返回任何结果。
例如我有这个文档:
{
"_id" : ObjectId("5797833e9de6f8c5615a20f9"),
"id" : "28743915-9be0-427d-980d-5009bfe1b13a",
"name" : "Hunter",
"rating" : 2.9,
"downloads" : 5040
}
当尝试获取此文档时:
conn.Session.
DB("face").
C("papers").
Find(bson.M{"rating": 2.9}).
All(&papers) // papers is an instance of a slice struct.
它不会返回任何文档,但在 mongo shell 中执行相同操作会返回文档,例如:
db.papers.find({"rating": 2.9})
但是在 mongo shell 中这样做不会返回任何文档:
db.papers.find({"rating": "2.9"})
所以我认为问题可能在于,当 bson.M 被序列化时,它可能会将值转换为字符串,因为 bson.M 是一个map[string]接口(interface){}
这就是 Paper 结构的样子
type Paper struct {
ID string `json:"id,omitempty" bson:"id"`
Name string `json:"name,omitempty" bson:"name"`
Rating float64 `json:"rating" bson:"rating"`
Downloads int `json:"downloads" bson:"downloads"`
}
最佳答案
我正在尝试了解您的问题是什么,但不能。最令人困惑的部分是你的问题解释
I'm trying to fetch documents by a field of type int
Find(bson.M{"rating": 2.9}).
"rating" : 2.9
在哪个世界 2.9
是整数?
- Go 和 Mongo 都没有类型
number
(您在标题中提到过)。 - 如果您使用
mgo
插入float64
,它会作为double
插入到Mongo 中。 - 您不能使用
string
查询来查询double
。所以db.papers.find({"rating": 2.9})
返回文档,而db.papers.find({"rating": "2.9"})
- 不,即使有一些文档带有"rating": 2.9
。
mgo
和mongo
都没有错误。如果您有兴趣,下面是使用您的 Paper
类插入 map 和检索数据的示例代码:
package main
import (
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
"fmt"
)
type Paper struct {
ID string `json:"id,omitempty" bson:"id"`
Name string `json:"name,omitempty" bson:"name"`
Rating float64 `json:"rating" bson:"rating"`
Downloads int `json:"downloads" bson:"downloads"`
}
func main() {
session, err := mgo.Dial("mongodb://127.0.0.1:27017/face")
if err != nil {
panic(err)
}
defer session.Close()
session.SetMode(mgo.Monotonic, true)
c := session.DB("face").C("papers")
c.Insert(bson.M{
"id": "28743915-9be0-427d-980d-5009bfe1b13a",
"name": "Hunter",
"rating": 2.9,
"downloads": 5040,
})
var papers []Paper
c.Find(bson.M{"rating": 2.9}).All(&papers) // equivalent of db.papers.find({"rating": 2.9})
fmt.Printf("%+v\n", papers)
}
关于mongodb - mgo:查找类型为 number (int, float64) 的字段不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38632832/