分享
在golang中使用mgo多条件查询
u012210379 · · 11822 次点击 · · 开始浏览这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。
今天被mgo凶残的语法折腾跪了 磨了1个多小时才搞出来 特此纪念:
一般做简单查询,是这样写的:
<pre name="code" class="plain">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,同时历史信息是reasona或reasonb的历史,如果直接用命令来查询,那简单的很,这样写就好:
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 我真心槽它大爷啊有疑问加站长微信联系(非本文作者)
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
关注微信11822 次点击
添加一条新回复
(您需要 后才能回复 没有账号 ?)
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码` - 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传
收入到我管理的专栏 新建专栏
今天被mgo凶残的语法折腾跪了 磨了1个多小时才搞出来 特此纪念:
一般做简单查询,是这样写的:
<pre name="code" class="plain">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,同时历史信息是reasona或reasonb的历史,如果直接用命令来查询,那简单的很,这样写就好:
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 我真心槽它大爷啊