duanbanzhi4419 2016-10-05 19:28
浏览 100
已采纳

查询两个字段之和小于给定值的地方

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 ).

  • 写回答

2条回答 默认 最新

  • dsieyx2015 2016-10-06 10:30
    关注

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度