如何使用Go语言从MongoDB数组中获取所有元素?

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

How to get all element from mongoDB array using go?

问题

我对mongodb和golang都非常陌生。我有一个名为"myplace"的集合,在其中有一个名为"region"的字段,它是一个值数组,我们如何检索整个数组。

我的集合如下所示:

{
"_id" : ObjectId("5474227309d76eb732acd134"),
"City" : "some city",
"region" : [
{
"regionid" : "31",
"historical_place" : "temple"
},
{
"regionid" : "32",
"historical_place" : "temple"
},
{
"regionid" : "33",
"historical_place" : "temple"
}
]
}

期望的输出是:

[
{
"City": "Some CIty",
"region":[
{
"regionid" : "31",
"historical_place" : "temple"
},
{
"regionid" : "32",
"historical_place" : "temple"
},
{
"regionid" : "33",
"historical_place" : "temple"
}
]
}
]

有什么解决方案吗?

英文:

I am very new to mongodb and golang. I have a collection named "myplace" inside that, one field named region which is an array of values how we can retrieve the whole array.

my collection look likes

{
"_id" : ObjectId("5474227309d76eb732acd134"),
"City" : "some city",
"region" : [ 
    {
        "regionid" : "31",
        "historical_place" : "temple"

    }, 
    {
        "regionid" : "32",
        "historical_place" : "temple"
    }, 
    {
         "regionid" : "33",
        "historical_place" : "temple"

    }
]
}

Expecting output

 [
  {
    "City": "Some CIty",
    "region":[ 
     {
        "regionid" : "31",
        "historical_place" : "temple"

     }, 
    {
        "regionid" : "32",
        "historical_place" : "temple"
    }, 
    {
         "regionid" : "33",
        "historical_place" : "temple"

    }
   ]
  }
]

Any solution?

答案1

得分: 4

使用bson标签创建结构体,并使用mgo的Find().All()方法。如果需要JSON输出,可以使用encoding/json包和MarshalIndent()函数:

package main

import (
	"encoding/json"
	"fmt"
	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
	"log"
)

type City struct {
	ID     bson.ObjectId `bson:"_id,omitempty" json:"-"`
	Name   string        `bson:"City"`
	Region []Place       `bson:"region"`
}

type Place struct {
	RegionID  string `bson:"regionid"`
	HistPlace string `bson:"historical_place"`
}

func main() {
	session, err := mgo.Dial("127.0.0.1")
	if err != nil {
		panic(err)
	}
	defer session.Close()

	c := session.DB("db").C("myplaces")

	var cities []City
	err = c.Find(nil).All(&cities)
	if err != nil {
		log.Fatal(err)
	}

	out, err := json.MarshalIndent(cities, " ", " ")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("Result:", string(out))
}
英文:

Create structs with bson tags and use mgo's Find().All().
And if you need an JSON output, use encoding/json package and MarshalIndent() function:

package main

import (
	"encoding/json"
	"fmt"
	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
	"log"
)

type City struct {
	ID     bson.ObjectId `bson:"_id,omitempty" json:"-"`
	Name   string        `bson:"City"`
	Region []Place       `bson:"region"`
}

type Place struct {
	RegionID  string `bson:"regionid"`
	HistPlace string `bson:"historical_place"`
}

func main() {
	session, err := mgo.Dial("127.0.0.1")
	if err != nil {
		panic(err)
	}
	defer session.Close()

	c := session.DB("db").C("myplaces")

	var cities []City
	err = c.Find(nil).All(&cities)
	if err != nil {
		log.Fatal(err)
	}

	out, err := json.MarshalIndent(cities, " ", " ")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("Result:", string(out))
}

答案2

得分: 0


import (
	"context"
	"encoding/json"
	"fmt"
	"log"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)


var (
	mongodbUrl = "mongodb://127.0.0.1:27017/"
)

type MyPlace struct {
	ID       primitive.ObjectID `json:"_id,omitempty" bson:"_id,omitempty"`
	City     string             `json:"city,omitempty" bson:"city,omitempty"`
	Regions  []Region           `json:"regions,omitempty" bson:"regions,omitempty"`
}

type Region struct {
	RegonID          string `json:"regionid,omitempty" bson:"regionid,omitempty"`
	HistoricalPlace  string `json:"historical_place,omitempty" bson:"historical_place,omitempty"`
}


func main() {
	var MyPlaces []MyPlace
	clientOptions := options.Client().
		ApplyURI(mongodbUrl)
	ctx := context.Background()
	
	client, err := mongo.Connect(ctx, clientOptions)
	if err != nil {
		log.Panic(err)
	}

	collection := client.Database("databseName").Collection("myplaces")

	cursor, err := collection.Find(ctx, bson.M{})
	if err != nil {
		log.Panic(err)
	}

	err = cursor.All(ctx, &MyPlaces)
	if err != nil {
		log.Panic(err)
	}

	data, err := json.Marshal(MyPlaces)
	if err != nil {
		log.Panic(err)
	}
	fmt.Println(string(data))
}

输出:

[
	{
		"_id" : "5474227309d76eb732acd134",
		"City" : "some city",
		"region" : [ 
				{
					"regionid" : "31",
					"historical_place" : "temple"

				}, 
				{
					"regionid" : "32",
					"historical_place" : "temple"
				}, 
				{
					"regionid" : "33",
					"historical_place" : "temple"

				}
			]
	},
	{
		"_id" : "5474227309d76eb732acd134",
		"City" : "some city",
		"region" : [ 
				{
					"regionid" : "31",
					"historical_place" : "temple"

				}, 
				{
					"regionid" : "32",
					"historical_place" : "temple"
				}, 
				{
					"regionid" : "33",
					"historical_place" : "temple"

				}
			]
	}
]
英文:

import (
	"context"
	"encoding/json"
	"fmt"
	"log"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)


var (
	mongodbUrl = "mongodb://127.0.0.1:27017/"
)

type MyPlace struct {
	ID					primitive.ObjectID		`json:"_id,omitempty" bson:"_id,omitempty"`
	City				string					`json:"city,omitempty" bson:"city,omitempty"`
	Regions				[]Region				`json:"regions,omitempty" bson:"regions,omitempty"`
}

type Region struct {
	RegonID				string					`json:"regionid,omitempty" bson:"regionid,omitempty"`
	HistoricalPlace		string					`json:"historical_place,omitempty" bson:"historical_place,omitempty"`
}


func main() {
	var MyPlaces []MyPlace
	clientOptions := options.Client().
		ApplyURI(mongodbUrl)
	ctx := context.Background()
	
	client, err := mongo.Connect(ctx, clientOptions)
	if err != nil {
		log.Panic(err)
	}

	collection := client.Database("databseName").Collection("myplaces")

	cursor, err := collection.Find(ctx, bson.M{})
	if err != nil {
		log.Panic(err)
	}

	err = cursor.All(ctx, &MyPlaces)
	if err != nil {
		log.Panic(err)
	}

	data, err := json.Marshal(MyPlaces)
	if err != nil {
		log.Panic(err)
	}
	fmt.Println(string(data))
}

Output:

[
	{
		"_id" : "5474227309d76eb732acd134",
		"City" : "some city",
		"region" : [ 
				{
					"regionid" : "31",
					"historical_place" : "temple"

				}, 
				{
					"regionid" : "32",
					"historical_place" : "temple"
				}, 
				{
					"regionid" : "33",
					"historical_place" : "temple"

				}
			]
	},
	{
		"_id" : "5474227309d76eb732acd134",
		"City" : "some city",
		"region" : [ 
				{
					"regionid" : "31",
					"historical_place" : "temple"

				}, 
				{
					"regionid" : "32",
					"historical_place" : "temple"
				}, 
				{
					"regionid" : "33",
					"historical_place" : "temple"

				}
			]
	}
]

huangapple
  • 本文由 发表于 2014年11月27日 15:55:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/27165692.html
匿名

发表评论

匿名网友

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

确定