我正在将Go语言和MongoDB与mgo.v2驱动程序一起使用,并且我的结构像
mgo.v2
type MarkModel struct { ID bson.ObjectId `json: "_id,omitempty" bson: "_id,omitempty"` Name string `json: "name" bson: "name"` Sum int `json: "sum" bson: "sum"` Delta int `json: "delta" bson: "delta"` }
我需要找到所有的地方Sum + Delta < 1000,例如。目前,我加载了所有内容,然后在Go代码中进行了过滤,但是我想在查询级别进行过滤。 如何进行查询?
Sum + Delta < 1000
此刻我归还
marks := []MarkModel{} c_marks := session.DB(database).C(marksCollection) err := c_marks.Find(bson.M{}).All(&marks) if err != nil { panic(err) }
在这里我在for循环中过滤了Go代码,但这不是最佳选择(这是不好的解决方案)。
要查找所有位置sum + delta < 1000,您可以使用:
sum + delta < 1000
pipe := c.Pipe( []bson.M{ bson.M{"$project": bson.M{"_id": 1, "name": 1, "sum": 1, "delta": 1, "total": bson.M{"$add": []string{"$sum", "$delta"}}}}, bson.M{"$match": bson.M{"total": bson.M{"$lt": 1000}}}, })
这是工作代码:
package main import ( "fmt" "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" ) func main() { session, err := mgo.Dial("localhost") if err != nil { panic(err) } defer session.Close() session.SetMode(mgo.Monotonic, true) // Optional. Switch the session to a monotonic behavior. c := session.DB("test").C("MarkModel") c.DropCollection() err = c.Insert(&MarkModel{bson.NewObjectId(), "n1", 10, 1}, &MarkModel{bson.NewObjectId(), "n2", 20, 2}, &MarkModel{bson.NewObjectId(), "n1", 100, 1}, &MarkModel{bson.NewObjectId(), "n2", 2000, 2}) if err != nil { panic(err) } pipe := c.Pipe( []bson.M{ bson.M{"$project": bson.M{"_id": 1, "name": 1, "sum": 1, "delta": 1, "total": bson.M{"$add": []string{"$sum", "$delta"}}}}, bson.M{"$match": bson.M{"total": bson.M{"$lt": 1000}}}, }) r := []bson.M{} err = pipe.All(&r) if err != nil { panic(err) } for _, v := range r { fmt.Println(v["_id"], v["sum"], v["delta"], v["total"]) } fmt.Println() } type MarkModel struct { ID bson.ObjectId `json: "_id,omitempty" bson: "_id,omitempty"` Name string `json: "name" bson: "name"` Sum int `json: "sum" bson: "sum"` Delta int `json: "delta" bson: "delta"` }
输出:
ObjectIdHex("57f62739c22b1060591c625f") 10 1 11 ObjectIdHex("57f62739c22b1060591c6260") 20 2 22 ObjectIdHex("57f62739c22b1060591c6261") 100 1 101