登录
首页 >  Golang >  Go问答

如何编写 Golang bson-MongoDB

来源:stackoverflow

时间:2024-04-01 20:18:29 338浏览 收藏

“纵有疾风来,人生不言弃”,这句话送给正在学习Golang的朋友们,也希望在阅读本文《如何编写 Golang bson-MongoDB》后,能够真的帮助到大家。我也会在后续的文章中,陆续更新Golang相关的技术文章,有好的建议欢迎大家在评论留言,非常感谢!

问题内容

我试图为此 mongodb 查询编写 golang bson 查询,但不能。有人可以帮忙吗? 我可以使用命令查询 mongo shell

db.collection.find({"nftype": "smf"},{"_id": 0,"ipv4addresses": 1})

它给出了我想要的输出

[{ "ipv4addresses": ["198.51.100.1"]}]

现在我尝试为此查询编写一个 golang bson 以仅获取如上所示的 ipv4addresses 字段,但不能。 集合中的文档格式为

{
    "nfType": [
      "SMF"
    ],
    "nfStatus": [
      "REG"
    ],
    "sNssais": [
      {
        "sst": 1,
        "sd": "sd1"
      }
    ],
    "nsiList": [
      "NSI-ID1"
    ],
    "ipv4Addresses": [
      "198.51.100.1"
    ]
  }

解决方案


只需创建一个查找查询和另一个过滤器,然后在您的 mongo 连接中使用这些 findq 和过滤器

findq := bson.m{"nftype": "smf"}
    filter := bson.m{"_id": 0, "ipv4addresses": 1}
    data:=[]interface{}// i am using interface. you can use your actual object
mongo.db(dbname).c(collectionname).find(findq).select(filter).all(&data)
session, err := mgo.Dial(mgo_url)
if err != nil {
    panic(err)
}
c := session.DB(db).C(collection)
defer session.Close()

result := make([]map[string]interface{}, 0)
err = c.Find(bson.M(map[string]interface{}{"nfType": "SMF"})).All(&result)

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《如何编写 Golang bson-MongoDB》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>