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

我用上面的方法来查询下面列出的我的数据集::

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

但是上面的方法似乎不起作用我得到一个空白索引......我试图根据上面查询中存在的标签名称来获取特定的键值对,因为我已经提到了 cd 我应该只为主机获取值并且 appname 和 appserver 不应列在最终结果中,因为它不包含标记名 cd。谢谢

4

1 回答 1

0

我认为你需要这样的东西:

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

您需要$unwind第一个数组,在本例中为“SHK”。展开(展平)“SHK”后,唯一的数组是“Tags”字段。那么你就可以申请$filter运营商了。你也错过了[]你的$in情况。你写了:

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

但是 $in 运算符是这样构建的:

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

所以在这种情况下:

$in: ['$$fil', ["cd"]]
于 2017-11-19T20:30:01.843 回答