如何使用Golang从MongoDB中获取JSON数组中的嵌套值

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

how to get nested value from json array using golang from mongodb

问题

我正在使用以下JSON数据:

{
  "Requirement": [
    {
      "Id": 1,
      "Data": "String123"
    },
    {
      "Id": 2,
      "Data": "String456"
    },
    {
      "Id": 3,
      "Data": "String789"
    }
  ]
}

我想根据IdRequirement数组中提取特定Data的值。
如果"Data" = "String123",则应该显示"Data"["WED"]

我尝试了以下代码,但是无论Id如何,我都得到了所有的值。

英文:

I am having the below json

I want to extract the value of particular Data from Requirement array based on Id.
If "Data" = "String123" it should display the "Data" as ["WED"].

I tried this code

but I am getting all values irrespective of Id.

答案1

得分: 0

查询的结果是一组文档。如果你将组件的集合存储在一个文档中,即使在查询中使用了组件的字段,如果匹配了过滤条件,结果仍然会返回整个文档。

MongoDB支持选择你想要或不想要的属性,但是你不能根据它们的属性排除数组元素。
请注意,MongoDB支持仅返回数组的一部分($slice (projection)),但这是基于索引的,并不是你真正想要的。

你必须手动遍历返回文档(Eligibility)的组件,并搜索你想要的组件。或者根据文档的内容,你应该将其拆分为单独的文档来存储每个组件,然后你可以对它们进行过滤和单独检索。

英文:

The result of a query is a collection of documents. If you store the collection of components in one document, even though you use fields of components in the query, the result will still return the whole document if it matches the filters.

MongoDB supports selecting properties which you want or don't want, but you can't exclude array elements based on their properties.
Note that MongoDB supports returning only a part of an array ($slice (projection)) but that is index based and is not really what you want.

You have to manually go through the components of your returned documents (Eligibility) and search for the component you want. Or looking at the content of your document, you should split it to store each component as a separate document and then you can filter them and retrieve them individually.

答案2

得分: 0

如果我理解正确,您在"clOfferMaster"集合中有一条记录,并且您正在尝试从嵌套集合"Eligibility"中获取数据。这可能不是一种典型的数据处理方式。

如果您按照以下方式重新组织数据:

[
    {
        "ComponentId" : "SessionDayCheck",
        "ConfigData" : [
            "WED"
        ]
    },
    {
        "ComponentId" : "TransDayCheck",
        "ConfigData" : [
            "WED",
            "THU"
        ]
    },
    {
        "ComponentId" : "SessionTransCheck",
        "ConfigData" : ""
    }
]

在这种情况下,您可以执行以下查询:

c := session.DB("offerengine2").C("clOfferMaster")

var result struct {
    ConfigData []string "ConfigData"
}
err = c.Find(bson.M{"ComponentId": "SessionDayCheck"}).One(&result)
if err != nil {
    log.Fatal(err)
}

fmt.Println("Result:", result)
// Result: {[WED]}

这样您就可以从"ConfigData"字段中获取到结果。

英文:

If I get you right you have one record in "clOfferMaster" collection and you're trying to fetch data from nested collection "Eligibility". That's probably not a typical way to work with data.

What if you restructure your data as follows:

[ 
    {
        "ComponentId" : "SessionDayCheck",
        "ConfigData" : [ 
            "WED"
        ]
    }, 
    {
        "ComponentId" : "TransDayCheck",
        "ConfigData" : [ 
            "WED", 
            "THU"
        ]
    }, 
    {
        "ComponentId" : "SessionTransCheck",
        "ConfigData" : ""
    }
]

It that case you can do the following query

c := session.DB("offerengine2").C("clOfferMaster")

var result struct {
	ConfigData []string "ConfigData"
}
err = c.Find(bson.M{"ComponentId": "SessionDayCheck"}).One(&result)
if err != nil {
	log.Fatal(err)
}

fmt.Println("Result:", result)
// Result: {[WED]} 

huangapple
  • 本文由 发表于 2015年2月23日 18:37:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/28671786.html
匿名

发表评论

匿名网友

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

确定