在golang中使用mgo多条件查询

2017/08/24 posted in  Golang

今天被mgo凶残的语法折腾跪了

一般做简单查询,是这样写的:

collection := mgodbcontroller.GetMdb().C(mgodbcontroller.USER_WALLET_GS_LOG)//获取操作对象
//根据用户手机号 倒序查询前100个 存入slice中
if err := collection.Find(&bson.M{"uphone": phonenum}).Sort("-initimesamp").Limit(100).All(&historys); err == nil {

	for i, _ := range historys {
		fmt.Println("从mgo查询到的数据--->", historys[i])
		ms = append(ms, &historys[i])
	}

} else {
	fmt.Println("查询历史", err)
	logUtils.GetLog().Error("查询历史", err)
}

现在需要查询这些用户中,手机号为18112345678,同时历史信息是reasonareasonb的历史,如果直接用命令来查询,那简单的很,这样写就好:

db.userwalletgslog.find({"uphone":"18112345678","reason":{"$in":["reasona","reasonb"]}})

接下来,苦逼的问题来了,要用golang调用mgo来实现上面这个语句,咋整
百度N久,找到个这么写的:(链接是 http://blog.csdn.net/varding/article/details/17200299 )

c.Find(bson.M{"name": bson.M{"$in": []string{"Jimmy Kuu", "Tracy Yu"}}}).All(&users)

他的这个写法其实有点问题,至少我的程序里跑不起来,经过了长~~~~~~时间的测试:

答案在此:

err := collection.Find(&bson.M{"uphone": "18112345678", "reason": &bson.M{"$in": []string{"reasona", "reasonb"}}}).All(&historys)

看到了嘛,看到了嘛,这个坑爹的&bson.M 我真心TMD啊