需要帮助来编写MongoDB Query

时间:2014-06-03 07:00:59

标签: mongodb mapreduce mongodb-query

假设我的收藏中有以下文件:

{
   "Tag-1": "val-1",
   "Tag-2":
      {
        "S_Tag-1": {"SS_Tag_1":"SS_Tag_Val_1","SS_Tag_2":"SS_Tag_Val_2"},
        "S_Tag-2": {"SS_Tag_1":"SS_Tag_Val_3","SS_Tag_2":"SS_Tag_Val_3"},
        "S_Tag-3": {"SS_Tag_1":"SS_Tag_Val_1","SS_Tag_2":"SS_Tag_Val_2"},
      }
}

现在我想让所有S_Tag孩子的孩子有值"SS_Tag_Val_1"

预期输出为:

"S_Tag-1": {"SS_Tag_1":"SS_Tag_Val_1","SS_Tag_2":"SS_Tag_Val_2"}
"S_Tag-3": {"SS_Tag_1":"SS_Tag_Val_1","SS_Tag_2":"SS_Tag_Val_2"}

如何在MongoDB中实现这一目标?

提前致谢!

1 个答案:

答案 0 :(得分:0)

文档结构可能会更好地为您提供其他选项。但是你需要JavaScript处理来过滤和匹配这个,所以最好的方法是mapReduce:

db.collection.mapReduce(
    function () {

        var obj = {};
        var count = 0;

        for ( var t in this["Tag-2"] ) {

            for ( var k in this["Tag-2"][t] ) {
                if ( this["Tag-2"][t][k] === "SS_Tag_Val_1" ) {
                    obj[t] = this["Tag-2"][t];
                    count++;
                    break;
                }
            }

        }

        if ( count != 0 )
            emit( this._id, obj );

    },
    function(){},
    { "out": { "inline": 1 } }
)

给你:

    "results" : [
            {
                    "_id" : ObjectId("538ea58506bfa12156d3041a"),
                    "value" : {
                            "S_Tag-1" : {
                                    "SS_Tag_1" : "SS_Tag_Val_1",
                                    "SS_Tag_2" : "SS_Tag_Val_2"
                            },
                            "S_Tag-3" : {
                                    "SS_Tag_1" : "SS_Tag_Val_1",
                                    "SS_Tag_2" : "SS_Tag_Val_2"
                            }
                    }
            }
    ]

因此,您需要一些变体,以便您可以遍历您拥有的对象结构。由于设置路径,不是最好的查询。考虑使用数组来简化查询。