【问题标题】:How to retrieve []bson.M type of map如何检索 []bson.M 类型的地图
【发布时间】:2016-02-21 00:43:01
【问题描述】:

如何检索多维[]bson.M类型的地图

mongo中的数据是这样的

"taskData" : { 
    "createdOn" : ISODate("2016-02-20T21:23:11.903Z"), 
    "Task_content" : "@bob", 
    "Priority" : "2", 
    "owner_Uname" : "alice"
}

我试图访问它的代码

var n []bson.M
 e := collection.Find(bson.M{"users."+strconv.Itoa(j)+".user_name" :   r.FormValue("value[userName]")}).Select(bson.M{"taskData.owner_Uname":1,"_id":0}).All(&n)
if e != nil {
   fmt.Println("Error : ",e)
}else{
   fmt.Println(n[0]["taskData"])
}

得到这样的输出

map[owner_Uname:alice]

我需要使用另一个查询来访问这个结果字符串。 这是我试图将其转换为简单地图的界面 newMap :=n[0]["taskData"].(map[string]interface{})但它给了我一个运行时错误interface conversion: interface {} is bson.M, not map[string]interface {}

result := rawData{}
err := collection.Find(bson.M{"user_name":n[0]["taskData"]["owner_Uname"]}).All(&result)

现在我想在上面的查询中使用它... 请帮帮我。在此先感谢

编辑:- mongo中的数据是这样的

{
   "_id" : ObjectId("56bf128f5a9a6a0ebfdd5075"),
     "deadLine" : {
       "Start_time" : ISODate("2016-05-24T00:00:00Z"),
       "End_time" : ISODate("2016-05-29T00:00:00Z")
     },
   },
   "taskData" : { 
       "createdOn" : ISODate("2016-02-20T21:23:11.903Z"), 
       "Task_content" : "@bob", 
       "Priority" : "2", 
       "owner_Uname" : "alice"
   },
   "group" : {
      "1" : {
        "grp_name" : "grp"
       },
      "2" : {
        "grp_name" : "secondGrp"
       }
    }

如果使用嵌套结构或结构中的映射完成,我也可以这样做

【问题讨论】:

  • 不使用结构体有什么特殊原因吗?
  • 是否可以通过嵌套结构实现@Markus W Mahlberg
  • 当然。 ;) 我整天都在做。
  • 你能给我一个演示吗
  • 我在下面写了一个demo,但是有几点需要注意。 a)@RickyA 给了你一个有用的链接。如果你读得正确,你就会有你的解决方案。 b) 你在和同龄人交谈,要求一些东西。对于您想要实现的目标,“没有帮助”甚至是愚蠢的。如果您已经描述了链接没有帮助的方式,那么也许有人会有动力进一步帮助您。 c)您的示例数据在语法上不正确。下次请加minimal, complete and verifiable example。

标签: mongodb go struct bson mgo


【解决方案1】:

我将为您提供一个通用示例以帮助您理解,因为 SO 不是免费的编码服务,而是一个同行互相帮助以解决问题的平台。

我的方法是根本不使用 bson.M 作为返回值。

package main

import (
    "fmt"
    "time"

    "gopkg.in/mgo.v2"
    "gopkg.in/mgo.v2/bson"
)

type Baz struct {
    Date  time.Time
    Value int
}

type Bar struct {
    Name string
    Baz  []Baz
}

type Foo struct {
    Owner  string
    hidden int
    Bar    Bar
}

const (
    ds   = "localhost:27017"
    db   = "test"
    coll = "nestdemo"
)

func main() {

    o := Foo{
        Owner:  "me",
        hidden: 1,
        Bar: Bar{
            Name: "funky",
            Baz: []Baz{
                Baz{Date: time.Now(), Value: 42},
            },
        },
    }

    // CHECK ERRORS in production environments
    conn, _ := mgo.Dial(ds)
    defer conn.Close()

    c := conn.DB(db).C(coll)
    c.Insert(o)

    l := &Foo{}

    c.Find(bson.M{"owner": "me"}).One(l)

    fmt.Printf("Loaded data: %+v\n", l)
    fmt.Printf(
        "You got your answer to life, the universe and all the rest at %s: %d\n",
        l.Bar.Baz[0].Date.Format(time.Kitchen), l.Bar.Baz[0].Value,
    )
}

你可以在你的本地机器上运行这个程序(根据需要调整常量),它应该会给你一个如下所示的输出:

$ go run main.go 
Loaded data: &{Owner:me hidden:0 Bar:{Name:funky Baz:[{Date:2016-02-24 09:00:06.471 +0100 CET Value:42}]}}
You got your answer to life, the universe and all the rest at 9:00AM: 42

相应集合中的条目应如下所示:

{
  "_id" : ObjectId("56cd6306538ba56563bdab76"),
  "owner" : "me",
  "bar" : {
    "name" : "funky",
    "baz" : [
      {
        "date" : ISODate("2016-02-24T08:00:06.471Z"),
        "value" : 42
      }
    ]
  }
}

这里有几点需要注意。

  1. 我不需要在我的结构定义中使用单个字符来将结构编组到 BSON 和从 BSON 编组。它是由 mgo according to the rules described in the docs 自动完成的。但是,您可以自定义(取消)编组的行为,如那里所述。
  2. 未导出的字段(在此示例中为 hidden)在解组时取为零值 - 请记住,它可能会咬你的脖子。
  3. 无需使用 bson.M 来处理您的数据,这让生活变得更加轻松 - 例如,无需手动类型转换。

总而言之:您需要做的就是创建一个可以将您的数据解组为的结构。然后,您可以像往常一样访问各个字段,而无需摆弄字符串等。如您所见,这有点工作,但相当微不足道。

注意:您展示的数据模型在语法和概念上都不正确。暂时先把前者放在一边:将值作为键是一种非常糟糕的做法,如 group 子文档中所示。这将始终迫使您来回处理字符串解析,使您在 MongoDB 的生活变得像开发人员一样复杂。

我的上述建议假设您会将其更正为:

{
…
  groups:[
    {grp_id: 1, grp_name: "grp"},
    {grp_id: 2, grp_name: "secondGrp"}
  ]
…
}

【讨论】:

  • 感谢您为此付出的努力。
  • @RickyA 谢谢你,先生。让我们称之为手指练习?
猜你喜欢
  • 1970-01-01
  • 2023-03-29
  • 1970-01-01
  • 2014-01-02
  • 1970-01-01
  • 2016-06-18
  • 1970-01-01
  • 1970-01-01
  • 2019-10-17
相关资源
最近更新 更多