[英]Query where sum of two fields is less than given value
我正在将Go语言和MongoDB与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代码中进行过滤,但我想在查询级别进行过滤。
如何进行查询?
此刻我归还
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
所有位置,可以使用:
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
您确实应该为此使用Aggregation Framework 。 然后在服务器端处理。 做类似的事情:
db.table.aggregate(
[
{ $project: { ID: 1, name : 1, total: { $add: [ "$Sum", "$Delta" ] } } },
{ $match : { total : { $gte: 1000 }}}
]
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.