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我应该得到值因为它不包含标记名cd,所以不应该在最终结果中列出主机和appname和appserver。感谢
答案 0 :(得分: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"之后,唯一的数组是"标签"领域。那么您可以应用$filter
运算符。此外,您错过了[]
条件中的$in
。你写道:
{$in:['$$fil.Tags',"cd"]}
但$ in运算符是这样构建的:
{ $in: [ <expression>, <array expression> ] }
所以在这种情况下:
$in: ['$$fil', ["cd"]]