亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Mongodb collection.Find() 返回過濾后的數據

Mongodb collection.Find() 返回過濾后的數據

Go
慕絲7291255 2022-06-13 16:45:43
我想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    }}
查看完整描述

2 回答

?
慕桂英546537

TA貢獻1848條經驗 獲得超10個贊

首先,MongoDB 在應用程序運行時進行連接。


func main() {

    mongoDB()

    server := routerV1()

    server.Run(os.Getenv("PORT"))

}

var collection *mongo.Collection


func 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 的命令行上做我想做的過濾時,我可以得到我想要的結果。


查看完整回答
反對 回復 2022-06-13
?
冉冉說

TA貢獻1877條經驗 獲得超1個贊

  1. 如果您的 go 應用程序啟動,您必須首先連接您的 MongoDB 客戶端:

    clientOptions := options.Client().ApplyURI("mongodb://localhost:27017") 客戶端,錯誤 := mongo.Connect(context.TODO(), clientOptions)

  2. 獲取連接的 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 驅動程序包。


查看完整回答
反對 回復 2022-06-13
  • 2 回答
  • 0 關注
  • 343 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號