查询两个字段的总和小于给定值的查询

时间:2016-10-05 19:28:37

标签: mongodb go bson mgo

我使用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代码,但它不是最优的(这是一个糟糕的解决方案)。

2 个答案:

答案 0 :(得分:2)

要找到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

答案 1 :(得分:1)

你应该真的使用Aggregation Framework。然后它处理服务器端。做类似的事情:

db.table.aggregate(
   [
     { $project: { ID: 1, name : 1, total: { $add: [ "$Sum", "$Delta" ] } } },
     { $match : { total  : { $gte: 1000 }}}
   ]
)
相关问题