Mongodb集合.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
}
for cursor.Next(context.TODO()) {
var project Project
cursor.Decode(&project)
projects = append(projects, project)
}
c.JSON(http.StatusOK, &projectListResponse{
Status:          http.StatusOK,
Description:     "All registered projects are listed successfully",
DatabaseMessage: "No error",
Projects:        projects,
})
return
}
{
"status": 200,
"description": "All registered projects are listed successfully",
"database_message": "No error",
"projects": [
{
"id": "000000000000000000000000",
"project_name": "Testxx 123",
"tags": [
{
"tag_name": "asdasd",
"order": 1
}
],
"type": 1,
"constituent": "1",
"cover_photo": "",
"ratio": "x",
"width": "100",
"height": "200",
"users": [
{
"user_id": "1"
},
{
"user_id": "2"
}
],
"created_at": "2020-07-07T12:10:06.861Z",
"updated_at": "0001-01-01T00:00:00Z"
},
{
"id": "000000000000000000000000",
"project_name": "Test 12233",
"tags": [
{
"tag_name": "asdasd",
"order": 1
}
],
"type": 1,
"constituent": "1",
"cover_photo": "",
"ratio": "x",
"width": "100",
"height": "200",
"users": [
{
"user_id": "1"
},
{
"user_id": "2"
}
],
"created_at": "2020-07-07T12:10:29.394Z",
"updated_at": "0001-01-01T00:00:00Z"
},
{
"id": "000000000000000000000000",
"project_name": "Test 12233",
"tags": [
{
"tag_name": "asdasd",
"order": 1
}
],
"type": 1,
"constituent": "1",
"cover_photo": "",
"ratio": "x",
"width": "100",
"height": "200",
"users": [
{
"user_id": "5"
},
{
"user_id": "2"
}
],
"created_at": "2020-07-07T12:10:29.394Z",
"updated_at": "0001-01-01T00:00:00Z"
}
]
}
  1. 如果你的go应用程序启动,你必须首先连接你的MongoDB客户端:

    clientOptions:=选项。客户端((.ApplyURI(";mongodb://localhost:27017"(客户端,err:=mongo。Connect(context.TDO((,clientOptions(

  2. 连接MongoDB客户端进行查询:

    collection:=客户端。数据库("Database"(。集合("Collection"(cur,err:=集合。查找(context.TDO((,bson。D{{}},findOptions(

您的代码中只有查询。您没有结果,因为您没有要收集的数据库和集合。Find((:

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

MongoDB Go驱动程序教程是CRUD操作的一个很好的起点。Go驱动程序教程中的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驱动程序包。

首先,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{})

问题;当我过滤以返回"0"时,返回空结果;users:["user_id":"1"]";。

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

正如我所说,连接没有问题。如果不进行筛选,则返回所有结果。当我按照自己想要的方式进行筛选时,会返回空结果。

当我在mongo上的命令行上进行我想进行的过滤时,我可以得到我想要的结果。

谢谢

最新更新