要查找所有位置
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 mainimport ( "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 11ObjectIdHex("57f62739c22b1060591c6260") 20 2 22ObjectIdHex("57f62739c22b1060591c6261") 100 1 101
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)