如何在深度嵌套文档中根据标签名称搜索 mongodb 中的键值?
How to search a key value in mongodb based on tag name in a deeply nested document?
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。谢谢
我想你需要这样的东西:
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"]]
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。谢谢
我想你需要这样的东西:
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"]]