mgo:查找数字类型(int,float64)的字段不起作用

I'm developing a RESTful API in go with the mgo driver for the MongoDB.

The problem is that I'm trying to fetch documents by a field of type int and no results is returned.

For example I have this document:

{
  "_id" : ObjectId("5797833e9de6f8c5615a20f9"),
  "id" : "28743915-9be0-427d-980d-5009bfe1b13a",
  "name" : "Hunter",
  "rating" : 2.9,
  "downloads" : 5040
}

And when trying to fetch this document with:

conn.Session.
    DB("face").
    C("papers").
    Find(bson.M{"rating": 2.9}).
    All(&papers) // papers is an instance of a slice struct.

It will not return any documents but doing the same in a mongo shell returns documents, for example:

db.papers.find({"rating": 2.9})

But doing this in the mongo shell won't return any documents:

db.papers.find({"rating": "2.9"})

So I think that the problem might be that when bson.M is being serialized it might convert the value to a string, because that bson.M is a map[string]interface{}

This is how the Paper struct looks like

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 understand what is your problem and can't. Most confusing part is your problem explanation

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

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

  3. "rating" : 2.9

In which world 2.9 is an integer?

  1. There is no type number (which you have mentioned in title) nor in Go, nor in Mongo.
  2. If you are inserting float64 with mgo it's inserted into Mongo as double
  3. You can't query double with string query. So db.papers.find({"rating": 2.9}) returns documents and db.papers.find({"rating": "2.9"}) - not, even if there are a few documents with "rating": 2.9.

There is no error in mgo nor in mongo. If you are interested, here is the sample code that inserts map and retrieves data with your Paper class:

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
", papers)
}