0
 db.props.aggregate([{"$match":{release:"1"}},{"$project":{'_id':0, 'SHK.0':{"$filter":{"input":'$SHK.0.host',"as":'fil', "cond":{$in:['$$fil.Tags',"cd"]}}}}}])

I used the above to query my dataset listed below ::

{ "_id" : ObjectId("5a0eafdf481fc70d171521b1"), 
    "release" : "1", 
    "product" : "1", 
    "project" : "1", 
    "patchset" : "1", 
    "common" : { 
        "active" : "YES", 
        "javahome" : "path" }, 
    "SHK" : [ 
        { 
        "host" : { 
            "value" : "demo", 
            "Tags" : [ "ci", "cd" ] }, 
        "appserver" : { 
                "value" : "demo", 
                "Tags" : [ "ci" ] }, 
        "appname" : { 
            "value" : "demo", 
            "Tags" : [ "cd" ] } } ] }

But the above does not seem to work I am getting a blank index ... I am trying to get here specific key value pair according to the tag name present suppose in the above query as i have mentioned cd i should get value for only host and appname and appserver should not be listed in the end result as it does not contain the tagname cd. Thanks

1 Answers1

0

I think you need something like that:

db.props.aggregate([{
        "$match": {
            release: "1"
        }
    },
    {
        $unwind: '$SHK'
    },
    {
        "$project": {
            '_id': 0,
            'tag': {
                "$filter": {
                    "input": '$SHK.host.Tags',
                    "as": 'fil',
                    "cond": {
                        $in: ['$$fil', ["cd"]]
                    }
                }
            }
        }
    }
])

You need to $unwind the first array, in this case "SHK". After unwinding (flattening) "SHK", the only array is the "Tags" field. So then you can apply the $filter operator. Also you were missing the [] in your $in condition. You wrote:

{$in:['$$fil.Tags',"cd"]}

but $in operator is build like that:

{ $in: [ <expression>, <array expression> ] }

so in this case:

$in: ['$$fil', ["cd"]]
Alex P.
  • 3,073
  • 3
  • 22
  • 33
  • This works well not exactly the output i wanted but gave me if a particular key contains that tag or not which I then compared programmatically and deleted the keys where these tags were not present. Thanks – Atharva Pandey Nov 21 '17 at 05:20