如何使用mongodb中的golang从json数组中获取嵌套值
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
.
我具有以下json p>
我要提取的值
如果 我尝试了此代码 p>
,但是我获得了所有值,而与“ Data” =“ String123” code>,则应将“ Data”显示为[“ WED “]。 p>
Id code>无关。 p>
div>
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]}
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.