doutuo6689
2015-02-23 10:37
浏览 131

如何使用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.

图片转代码服务由CSDN问答提供 功能建议

我具有以下json

我要提取的值 如果“ Data” =“ String123” ,则应将“ Data”显示为[“ WED “]。

我尝试了此代码

,但是我获得了所有值,而与 Id 无关。

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douhui8025 2015-02-23 11:42
    已采纳

    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]} 
    
    已采纳该答案
    打赏 评论
  • donglu1971 2015-02-23 11:34

    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.

    打赏 评论

相关推荐 更多相似问题