2 回答

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

TA貢獻1877條經驗 獲得超1個贊
如果您的 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 驅動程序包。
- 2 回答
- 0 關注
- 343 瀏覽
添加回答
舉報