drbz99867
2018-07-06 10:34
浏览 61

mongodb管道查询$ project中的错误应该是什么?

I'm pipeline my data in the mongodb collection but it will not returning any data to me the code is following:-

func GetLog(c *gin.Context) {
values := c.Query("value")
fmt.Println("value", values)
result := []bson.M{}
mongoSession := config.ConnectDb()
getCollection := mongoSession.DB(config.Database).C(config.LogCollection)
pipe := getCollection.Pipe([]bson.M{ 
            bson.M{"$unwind": "$booking_details"},
                bson.M{"$project": bson.M{
                "role":1,
                "date":1,
                "idadress":1,
                "booking":1,
                "booking_values":bson.M{"$objectToArray":"$booking"},
            } },
    bson.M{"$match": bson.M{
        "booking_values.v" : bson.RegEx{"(?i).*"+values+".*", "i"},
    }}, } )
fmt.Println(pipe)
err := pipe.All(&result)
fmt.Println(result)
}

In the values there will be string why this will not giving me any result. the data in mongodb is:

 {
  "_id": ObjectId("5b3d970398e9d099427896c3"),
  "role": "New Booking is there by abc",
  "date": "07/04/2018",
  "idaddress": "213.123.123.213",
  "booking": {
    "bedroom": 4,
    "bathroom": 6,
    "customer": "abc",
    "email": "abc@gmail.com",
    "provider": "provider1",
    "address": "brazil",
    "appt": "123456",
    "phone": "987654321"
 }
}

The struct is like given below:

 type Log struct {
Id              bson.ObjectId    `json:"_id" bson:"_id,omitempty"`
Role              string         `json:"role" bson:"role"`
Date              string         `json:"date" bson:"date"`
IpAddress         string         `json:"idaddress" bson:"idaddress"`
Booking           interface{}    `json:"booking" bson:"booking"`
}
type Logs []Log
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • doucheng9634 2018-07-06 11:03
    已采纳

    Change your pipe code to the below code:-

    pipe := getCollection.Pipe([]bson.M{ 
                    bson.M{"$project": bson.M{
                    "role":1,
                    "date":1,
                    "idaddress":1,
                    "booking":1,
                    "booking_values":bson.M{"$objectToArray":"$booking"},
                } },
        bson.M{"$match": bson.M{
            "booking_values.v" : bson.RegEx{"(?i).*"+values+".*", "i"},
        }}, } )
    

    to you don't have any booking_details field as the icza said so you have to remove it and then run your go code.

    评论
    解决 无用
    打赏 举报
查看更多回答(1条)

相关推荐 更多相似问题