为了账号安全,请及时绑定邮箱和手机立即绑定

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 关注
  • 302 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号