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 关注
- 302 浏览
添加回答
举报