猿问

Mongodb collection.Find() 返回过滤后的数据

我想user_id: 1用我在下面给出的代码将那些放在用户下面,但结果总是空的。


我没有收到任何错误,但我不完全理解我在哪里犯错误:/


*此外;


什么是bson.M{}什么bson.D{}。我不完全明白它们之间有什么区别?


type Project struct {

    ID          string          `json:"id"`

    ProjectName string          `json:"project_name"`

    Tags        []ProjectTags   `json:"tags"`

    Type        int             `json:"type"`

    Constituent string          `json:"constituent"`

    CoverPhoto  string          `json:"cover_photo"`

    Ratio       string          `json:"ratio"`

    Width       string          `json:"width"`

    Height      string          `json:"height"`

    User        []ProjectUsers  `json:"users"`

    CreatedAt   time.Time       `json:"created_at"`

    UpdatedAt   time.Time       `json:"updated_at"`

}


type ProjectTags struct {

    TagName string `json:"tag_name"`

    Order   int    `json:"order"`

}


type ProjectUsers struct {

    UserID string `json:"user_id"`

}

import (

    "context"

    "net/http"


    "github.com/gin-gonic/gin"

    "go.mongodb.org/mongo-driver/bson"

)


type projectListResponse struct {

    Status          int       `json:"status"`

    Description     string    `json:"description"`

    DatabaseMessage string    `json:"database_message"`

    Projects        []Project `json:"projects"`

}


func ProjectList(c *gin.Context) {

    projects := []Project{}

    cursor, err :=  (context.TODO(), bson.M{"users": bson.M{"$elemMatch": bson.M{"user_id": "1"}}})

    if err != nil {

        c.JSON(http.StatusInternalServerError, &projectListResponse{

            Status:          http.StatusInternalServerError,

            Description:     "There is problems with listing projects",

            DatabaseMessage: err.Error(),

            Projects:        projects,

        })

        return

    }

}


慕丝7291255
浏览 303回答 2
2回答

慕桂英546537

首先,MongoDB 在应用程序运行时进行连接。func main() {    mongoDB()    server := routerV1()    server.Run(os.Getenv("PORT"))}var collection *mongo.Collectionfunc dashboard(c *mongo.Database) {    collection = c.Collection("dashboard")}func mongoDB() {    // Database Config    clientOptions := options.Client().ApplyURI(os.Getenv("MONGODB"))    client, err := mongo.NewClient(clientOptions)    // Set up a context required by mongo.Connect    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)    err = client.Connect(ctx)    // To close the connection at the end    defer cancel()    err = client.Ping(context.Background(), readpref.Primary())    if err != nil {        log.Fatal("Couldn't connect to the database", err)    }    mongoDB := client.Database("databasename")    dashboard(mongoDB)    return}当我这样查询时,所有数据都会返回。cursor, err := collection.Find(context.TODO(), bson.M{})问题; 当我过滤返回“用户:[”user_id“:”1“]”时返回空结果。cursor, err := collection.Find(context.TODO(), bson.M{"users": bson.M{"$elemMatch": bson.M{"user_id": "1"}}})正如我所说,连接没有问题。当我不过滤时,将返回所有结果。当我按我想要的方式过滤时,会返回空结果。当我在 mongo 的命令行上做我想做的过滤时,我可以得到我想要的结果。

冉冉说

如果您的 go 应用程序启动,您必须首先连接您的 MongoDB 客户端:clientOptions := options.Client().ApplyURI("mongodb://localhost:27017") 客户端,错误 := mongo.Connect(context.TODO(), clientOptions)获取连接的 MongoDB 客户端进行查询:collection := client.Database("DATABASE").Collection("COLLECTION") cur, err := collection.Find(context.TODO(), bson.D{{}}, findOptions)您的代码中只有查询。您没有结果,因为您没有用于 collection.Find() 的数据库和集合:   cursor, err :=  (context.TODO(), bson.M{"users": bson.M{"$elemMatch": bson.M{"user_id": "1"}}})MongoDB Go Driver Tutorial是 CRUD 操作的一个很好的起点。Go Driver Tutorial 中的 MongoDB 驱动程序 bson 类型描述:D: A BSON document. This type should be used in situations where order matters, such as MongoDB commands.M: An unordered map. It is the same as D, except it does not preserve order.A: A BSON array.E: A single element inside a D.您可以在此处查看 bson的官方 MongoDB Go 驱动程序包。
随时随地看视频慕课网APP

相关分类

Go
我要回答