Query where sum of two fields is less than given value

江枫思渺然 提交于 2019-12-13 10:18:34

问题


I am using Go language and MongoDB with mgo.v2 driver and I have struct like

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"`
}

I need to find all where is Sum + Delta < 1000 for example. At the moment I load all and then in Go code I filter but I would like to filter on query level.
How to make that query ?

At the moment I return all with

marks := []MarkModel{}
c_marks := session.DB(database).C(marksCollection)
err := c_marks.Find(bson.M{}).All(&marks)
if err != nil {
    panic(err)
}

and here I filter in Go code in for loop but it is not optimal ( it is bad solution ).


回答1:


To find all where is sum + delta < 1000, you may use:

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

Here is the working code:

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"`
}

output:

ObjectIdHex("57f62739c22b1060591c625f") 10 1 11
ObjectIdHex("57f62739c22b1060591c6260") 20 2 22
ObjectIdHex("57f62739c22b1060591c6261") 100 1 101



回答2:


You should really use the Aggregation Framework for this. Then it's handled server side. do something like :

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


来源:https://stackoverflow.com/questions/39882159/query-where-sum-of-two-fields-is-less-than-given-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!