Question

Let's say I have the following documents in my collection:

{
   "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"},
      }
}

Now I want to get all children of S_Tag whose child have value "SS_Tag_Val_1"

Expected output would be:

"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"}

How to achieve that in MongoDB?

Thanks in advance!

Was it helpful?

Solution

The document structure could be better to give you other options. But you are going to need JavaScript processing to filter and match this so the best approach is 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 } }
)

Gives you:

    "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"
                            }
                    }
            }
    ]

So you need some variant of that for your actual case where you can traverse the object structure you have. Not the best thing to query due to the set paths. Consider using arrays to make queries easier.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top