需要帮助编写MongoDB查询



假设我的集合中有以下文档:

{
   "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中实现?

提前感谢!

文档结构可以更好地为您提供其他选项。但你需要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"
                            }
                    }
            }
    ]

所以在实际情况中你需要它的一些变体你可以遍历你的对象结构。由于路径设置,这不是最好的查询。考虑使用数组来简化查询。

相关内容

  • 没有找到相关文章

最新更新