mongodb - mgo:查找类型为 number (int, float64) 的字段不起作用

标签 mongodb go mgo

我正在为 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"`
}

最佳答案

我正在尝试了解您的问题是什么,但不能。最令人困惑的部分是你的问题解释

  1. I'm trying to fetch documents by a field of type int

  2. Find(bson.M{"rating": 2.9}).

  3. "rating" : 2.9

在哪个世界 2.9 是整数?

  1. Go 和 Mongo 都没有类型 number(您在标题中提到过)。
  2. 如果您使用mgo 插入float64,它会作为double 插入到Mongo 中。
  3. 您不能使用string 查询来查询double。所以 db.papers.find({"rating": 2.9}) 返回文档,而 db.papers.find({"rating": "2.9"}) - 不,即使有一些文档带有 "rating": 2.9

mgomongo 都没有错误。如果您有兴趣,下面是使用您的 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/

相关文章:

Mongodb低基数索引

javascript - 如何在 mongoose (node.js) 中为产品系统定义不同的属性

go - 在 Golang 中构建没有 GitHub 的本地导入

json - 从 json post 请求中转义 html

mongodb - 在mongodb中按日期查询

mongodb - 自定义 mgo upsert 操作

同一列的日期和字符串格式的 MongoDB 日期

mongodb - 在mongodb中使用按位运算进行查询

reflection - 动态获取golang接口(interface)名称

mongodb - Go Lang 和 Labix mgo - 在后续请求后获取 EOF