1

For the below document, I need to output

1. image arrays which are hsl:1 
2. dim.hsl embedded document

The main document

{
"_id" : ObjectId("564b17873b91989fcb4e9707"),
"type" : "article",
"image" : [ 
    {
        "name" : "i3",
        "hsl" : 1
    }, 
    {
        "name" : "i1",
        "hsl" : 1
    }, 
    {
        "name" : "i2",
        "hsl" : 0,
        "ai" : 1
    }
],
"dim" : {
    "hsl" : {
        "path" : "blah"
    },
    "ai" : {
        "path" : "blah"
    }
}

My expected output is as below which returns 2 documents from image array and the dim.hsl embedded document

{
    "result" : [ 
        {
            "_id" : ObjectId("564b17873b91989fcb4e9707"),
            "type" : "article",
            "image" : [ 
                {
                    "name" : "i3",
                    "hsl" : 1
                }, 
                {
                    "name" : "i1",
                    "hsl" : 1
                }
            ],
            "dim" : {
                "hsl" : {
                    "path" : "blah"
                }
            }
        }
    ],
    "ok" : 1.0000000000000000
}

The code attempted below is not returning dim.hsl embedded document back. The logic is included in the code as inline. I am not sure on mongodb expressions for checking node presence. So i have used {$not : {$not : '$hsl'}}. (I hope there is a better way) Suggestions please.

db.survey.aggregate([
{ $match: { 
     image: { $elemMatch: {hsl: 1}}, //  docs which have image.hsl 
     'dim.hsl': { $exists: true} // docs which have dim.hsl
}},
{ $redact : {
     $cond: {
         if: { $or : [
                 {$eq: ['$hsl',1]}, // for image array document with hsl:1
                 {$eq : ['$type' ,'article']},// for main document node
                 {$not : {$not : '$hsl'}} // for dim -- NOT WORKING
             ]},
         then: "$$DESCEND",
         else: "$$PRUNE"
     }
}}]);

2 Answers 2

2

The problem why $redact cannot work like this is because of $$DESCEND and what it does. The expression basically means that the document is being inspected "at each level" to determine whether the conditions are met or not. So even if you put in a correct test for the "hsl" key being present, it is still going to "descend" to "path", where that condition is not going to be true, and therefore no content is valid to return further up the tree.

The only real appoach here is to "ignore" that key altogether, by basically providing a $$ROOT inspection at all levels and not touch that embedded part of the document. Then of course you can strip out the undesired values with $project later:

db.doc.aggregate([
    { "$match": {
        "image.hsl": 1,
        "dim.hsl": { "$exists": true }
    }},
    { "$redact": {
         "$cond": {
            "if": { 
                "$or": [
                     { "$eq": ['$hsl',1]},
                     { "$eq": ['$type' ,'article']},
                     { "$ifNull": [ "$$ROOT.dim.hsl", false ] }
                 ]
            },
            "then": "$$DESCEND",
            "else": "$$PRUNE"
         }
    }},
    { "$project": {
        "type": 1,
        "image": 1,
        "dim": {
            "hsl": "$dim.hsl"
        }
    }}
])

But of course that does not really remove anything as the $ROOT condition is always true, and that negates the point of the operation.

So instead filter out the elements using $map and $setDifference:

db.doc.aggregate([
    { "$match": {
        "image.hsl": 1,
        "dim.hsl": { "$exists": true }
    }},
    { "$project": {
        "type": 1,
        "image": { 
            "$setDifference": [
                { "$map": {
                    "input": "$image",
                    "as": "el",
                    "in": {
                        "$cond": [
                            { "$eq": [ "$$el.hsl", 1 ] },
                            {
                                "name": "$$el.name",
                                "hsl": "$$el.hsl"
                            },
                            false
                        ]
                    }
                }},
                [false]
            ]
        },
        "dim": {
            "hsl": "$dim.hsl"
        }
    }}
])

That actually "filters" the array content by inspecting each element with $map and then returning only the wanted fields on a postive true condtion, alternately a false value is returned instead of the array element. You then remove all falsevalues from the array by comparing to another array/set which has [false], the result is only the returned matches.

The other sub-key projection remains the same, and now of course all the removal is done only in a single $project stage.

And that returns the result you want:

{
    "_id" : ObjectId("564b17873b91989fcb4e9707"),
    "type" : "article",
    "image" : [
            {
                    "name" : "i3",
                    "hsl" : 1
            },
            {
                    "name" : "i1",
                    "hsl" : 1
            }
    ],
    "dim" : {
            "hsl" : {
                    "path" : "blah"
            }
    }
}
8
  • also this doc need to be removed { "name" : "i2", "hsl" : 0, "ai" : 1 } from the output as well. .. and { "$ifNull": [ "$$ROOT.dim.hsl", false ] } doesnt make any difference if it is either true/false.. chat? Commented Nov 18, 2015 at 7:52
  • @faiz Of course. $$ROOT.dim.hsl would always return true under the query conditions and therefore nothing gets removed. So there is another way to do this as added to the explanation. Commented Nov 18, 2015 at 8:01
  • I am evaluating your answer and I get this. "errmsg" : "exception: Expression $setDifference takes exactly 2 arguments. 1 were passed in.", Commented Nov 18, 2015 at 8:07
  • @faiz Missing a comma after the $map is all. Commented Nov 18, 2015 at 8:08
  • yes. figured the missing coma. possible to give inline code explanation of your answer. - need to read your mind :). thanks! Commented Nov 18, 2015 at 8:10
2

using redact to solve the above problem.

db.survey.aggregate([
    { "$match": {
        "image.hsl": 1,
        "dim.hsl": { "$exists": true }
    }},
    { "$redact": {
         "$cond": {
            "if": { 
                "$or": [
                     { "$eq": ['$hsl',1]},
                     { "$eq": ['$type' ,'article']},
                     { "$ifNull": [ "$hsl",  false] },
                     { "$ifNull": [ "$$CURRENT.path",  false] }
                 ]
            },
            "then": "$$DESCEND",
            "else": "$$PRUNE"
         }
    }},
    { "$project": {
        "type": 1,
        "image": 1,
        "dim": {
            "hsl": "$dim.hsl"
        }
    }}
])
4
  • 1
    Well thought. Testing for the underlying path field would be sufficient here. It's still using one more pipeline stage than you need to though, and each stage creates a cost. The $map and $setDifference combination I used gets replaced by $filter in the next MongoDB release anyway, which makes it more flexible and not tied to returning "sets" of unique entries only. Commented Nov 18, 2015 at 8:33
  • ty. Testing for path alone wouldn't return back the dim. The projection pipeline is an additional overhead. i didnt follow 'sets' of unique entries Commented Nov 18, 2015 at 11:35
  • A "set" ( think math ) implies "unique" values, so any array entry combination that had all the same values for keys as another would be reduced to a single entry via $setDifference, i.e [1,1,2,3] becomes [1,2,3] ( and not necessarily ordered ). That's just the nature of "sets". $filter is the answer to this from MongoDB 3.2 and onwards. $redact works, but it is not the most performant solution to solve this, as mentioned. Props for finding a condition to make it work, but it's not the best solution. Commented Nov 18, 2015 at 12:18
  • I chose to proceed with your answer in my solution and in SO also - using map in projection. your detailed explanation in answer and comments helped and gave more insights. Thank you once again. Commented Nov 18, 2015 at 12:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.