MongoDB切片查询到golang [英] MongoDB slice query into golang

查看:89
本文介绍了MongoDB切片查询到golang的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将下面的切片查询写到golang中?

How can i write this below slice query into golang?

db.con.find({"repoid":1356485},{"contr":{$slice:[0,10]}}).pretty()

尝试过但不起作用

DB.C("con").Find(bson.M{"id": ID, "contr": bson.M{"$slice": []interface{}{"$contr", offset, limit}}})

找不到任何东西.有什么想法吗?

does not find anything. Any ideas?

提前谢谢

推荐答案

使用 Collection.Find() 您只能指定过滤器.但是您所拥有的只是一个预测:

With Collection.Find() you can only specify the filter. But what you have is a projection:

{"contr":{$slice:[0,10]}

可以使用 Query.Select() 指定投影如何在投影中应用$slice

var results []bson.M // Use your own type here, but this works too

err := DB.C("con").Find(bson.M{"id": ID}).Select(bson.M{
    "contr": bson.M{"$slice": []int{offset, limit}},
}).All(&results)

// handle error

还请注意,过滤依据的属性是"id"还是仅仅是错字,应该是"_id".如果是后者,您还可以使用 Collection.FindId() 来查询文件编号:

Also note sure if the property you filter by is "id" or is just a typo and it should be "_id". If the latter, you may also use Collection.FindId() to query by document ID:

err := DB.C("con").FindId(ID).Select(bson.M{
    "contr": bson.M{"$slice": []int{offset, limit}},
}).All(&results)

这篇关于MongoDB切片查询到golang的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆