使用mgo在golang中从Mongodb选择列。

huangapple go评论73阅读模式
英文:

Select column from Mongodb in golang using mgo

问题

据我所知,我们可以使用以下代码来选择集合中的所有文本:

db['twitter-3'].find({}, {'text': 1})

在Golang中,我们如何使用mgo来查找特定字段呢?我尝试了以下代码,但是不正确:

var result []string
err = conn.Find(bson.M{}, bson.M{"text": 1}).All(&result)

请问正确的写法是什么?

英文:

As I know, we can use

> db['twitter-3'].find({}, {"text": 1})

to select all texts in collection.

How can we use mgo to find specific field in golang?
I tried

var result []string
err = conn.Find(bson.M{}, bson.M{"text", 1}).All(&result)

But it is not correct.

答案1

得分: 26

使用查询Select方法来指定要返回的字段:

var result []struct{ Text string `bson:"text"` }
err := c.Find(nil).Select(bson.M{"text": 1}).All(&result)
if err != nil {
    // 处理错误
}
for _, v := range result {
    fmt.Println(v.Text)
}

在这个例子中,我声明了一个匿名类型,其中只选择了一个字段。也可以使用包含所有文档字段的类型。

英文:

Use the query Select method to specify the fields to return:

var result []struct{ Text string `bson:"text"` }
err := c.Find(nil).Select(bson.M{"text": 1}).All(&result)
if err != nil {
    // handle error
}
for _, v := range result {
     fmt.Println(v.Text)
}

In this example, I declared an anonymous type with the one selected field. It's OK to use a type with all document fields.

答案2

得分: 2

选择多个字段:

var result []struct{
    Text string `bson:"text"`
    Otherfield string `bson:"otherfield"`
}

err := c.Find(nil).Select(bson.M{"text": 1, "otherfield": 1}).All(&result)
if err != nil {
   // 处理错误
}
for _, v := range result {
    fmt.Println(v.Text)
}
英文:

to select multiple fields:

var result []struct{
    Text string `bson:"text"`
    Otherfield string `bson:"otherfield"`
}

err := c.Find(nil).Select(bson.M{"text": 1, "otherfield": 1}).All(&result)
if err != nil {
   // handle error
}
for _, v := range result {
    fmt.Println(v.Text)
}

答案3

得分: 0

以下是要翻译的内容:

var result interface{}
err = c.Find(nil).Select(bson.M{"text": 1}).All(&result)

翻译结果:

var result interface{}
err = c.Find(nil).Select(bson.M{"text": 1}).All(&result)
英文:
var result interface{}
err = c.Find(nil).Select(bson.M{"text": 1}).All(&result)

huangapple
  • 本文由 发表于 2015年6月29日 21:05:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/31116528.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定