How to retrieve unstructured form of data from mongo using go map

huangapple go评论116阅读模式
英文:

How to retrieve unstructured form of data from mongo using go map

问题

我正在尝试使用go map检索数据。Mongo中的数据如下所示:

  1. "_id" : ObjectId("56bf128f5a9a6a0ebfdd5075"),
  2. "deadLine" : {
  3. "Start_time" : ISODate("2016-05-24T00:00:00Z"),
  4. "End_time" : ISODate("2016-05-29T00:00:00Z")
  5. },
  6. "taskData" : {
  7. "Task_content" : "Something",
  8. "Priority" : "3"
  9. },
  10. "group" : {
  11. "1" : {
  12. "grp_name" : "grp"
  13. },
  14. "2" : {
  15. "grp_name" : "secondGrp"
  16. }
  17. }

我想根据Priority检索所有记录。

我尝试的示例代码如下:

  1. var m []bson.M
  2. err := collection.Find(bson.M{"taskData": bson.M{"Priority": "2"}}).All(&m) // 在`Find()`这里卡住了
  3. if err != nil {
  4. fmt.Println("Error: ", err)
  5. } else {
  6. fmt.Println("Map: ", m)
  7. }

如果我使用

err := collection.Find(bson.M{"_id": bson.ObjectIdHex("56bf128f5a9a6a0ebfdd5075")}).All(&m)

那么它会获取所有记录。

请帮我纠正错误。

提前感谢。

英文:

I'm trying to retrieve data using go map. The data in mongo is like

  1. "_id" : ObjectId("56bf128f5a9a6a0ebfdd5075"),
  2. "deadLine" : {
  3. "Start_time" : ISODate("2016-05-24T00:00:00Z"),
  4. "End_time" : ISODate("2016-05-29T00:00:00Z")
  5. },
  6. "taskData" : {
  7. "Task_content" : "Something",
  8. "Priority" : "3"
  9. },
  10. "group" : {
  11. "1" : {
  12. "grp_name" : "grp"
  13. },
  14. "2" : {
  15. "grp_name" : "secondGrp"
  16. }
  17. }

And I want to retrieve all records according to Priority.

the sample code which i tried ...

  1. var m []bson.M
  2. err := collection.Find(bson.M{"taskData":bson.M{"Priority" : "2"}}).All(&m) // stuck here in `Find()`
  3. if err != nil {
  4. fmt.Println("Error : ",err)
  5. }else{
  6. fmt.Println("Map : ",m)
  7. }
  8. }

If i use
err := collection.Find(bson.M{"_id":bson.ObjectIdHex("56bf128f5a9a6a0ebfdd5075")}).All(&m)
then it fetch all records.
Kindly correct my mistake.

Thanks in advance

答案1

得分: 0

以下是要翻译的内容:

  1. var m []bson.M
  2. err := collection.Find(bson.M{"taskData.Priority" : "2"}).All(&m)
  3. if err != nil {
  4. fmt.Println("错误:",err)
  5. }else{
  6. fmt.Println("映射:",m)
  7. }
  8. }

这是一个描述:
https://docs.mongodb.org/manual/tutorial/query-documents/#equality-match-on-fields-within-an-embedded-document

英文:
  1. var m []bson.M
  2. err := collection.Find(bson.M{"taskData.Priority" : "2"}).All(&m)
  3. if err != nil {
  4. fmt.Println("Error : ",err)
  5. }else{
  6. fmt.Println("Map : ",m)
  7. }
  8. }

Here is the description
https://docs.mongodb.org/manual/tutorial/query-documents/#equality-match-on-fields-within-an-embedded-document

huangapple
  • 本文由 发表于 2016年2月15日 20:15:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/35409153.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定