[英]Get multiple matched elements from the double nested array of objects mongodb
The main collection document contains the workflow details.主集合文档包含工作流详细信息。 Each workflow details, there is a workflowState Object and in that there is an array of objects in the link.每个工作流详细信息都有一个工作流状态对象,并且链接中有一个对象数组。
I need to find all the matched objects from links array when from.nodeId = "value"当 from.nodeId = "value" 时,我需要从 links 数组中找到所有匹配的对象
{
"workflowId": "YNmwuXwQKElY",
"name": "Hello ",
"workflowState": {
"searchType": "tasks",
"links": [
{
"id": "67dca090-dd7a-4b86-8522-456ccdb891b2",
"from": {
"nodeId": "NecHqBJvxk",
"portId": "port1"
},
"to": {
"nodeId": "NecHqBJvxk",
"portId": "port2"
}
},
{
"id": "9b7a4d78-d4e6-4229-a091-24f87e3e1fa4",
"from": {
"nodeId": "PEfgrTpFOB",
"portId": "port2"
},
"to": {
"nodeId": "nUjhZhIwky",
"portId": "port1"
},
"headerValue": "Identifiers"
},
{
"id": "6e3fb202-7e29-46e0-b940-a4908ae8bb95",
"from": {
"nodeId": "NecHqBJvxk",
"portId": "port2"
},
"to": {
"nodeId": "PEfgrTpFOB",
"portId": "port1"
},
"headerValue": "Conditions",
}
],
"hovered": {},
},
"archive": true
}
I have tried this query我试过这个查询
db.collection.find({
"workflowState.links": {
$elemMatch: {
"from.nodeId": "NecHqBJvxk"
}
}
},
{
"workflowState.links.$": 1
})
but it is returning only the first match from the array.但它只返回数组中的第一个匹配项。
I expected the output in this format.我期望这种格式的输出。
{
"_id": ObjectId("5a934e000102030405000000"),
"workflowState": {
"links": [
{
"from": {
"nodeId": "NecHqBJvxk",
"portId": "port1"
},
"id": "67dca090-dd7a-4b86-8522-456ccdb891b2",
"to": {
"nodeId": "NecHqBJvxk",
"portId": "port2"
}
},
{
"id": "6e3fb202-7e29-46e0-b940-a4908ae8bb95",
"from": {
"nodeId": "NecHqBJvxk",
"portId": "port2"
},
"to": {
"nodeId": "PEfgrTpFOB",
"portId": "port1"
},
"headerValue": "Conditions"
}
]
}
}
How to get all the elements of the object from the array which matched the criteria?如何从符合条件的数组中获取对象的所有元素?
Thanks in advance提前致谢
Use Aggregate function with $unwind stage在 $unwind 阶段使用聚合函数
db.collection.aggregate([
// Match possible documents
{ "$match": {
"workflowState.links.from.nodeId": "NecHqBJvxk"
}},
// Unwind each array
{ "$unwind": "$workflowState.links" },
// Filter just the matching elements
{ "$match": {
"workflowState.links.from.nodeId": "NecHqBJvxk"
}},
// Group to inner array
{ "$group": {
"_id": "$_id",
"links": { "$push": "$workflowState.links" }
}},
{
"$project":{
_id: "$_id",
"workflowState.links": "$links",
}
}
]);
To get only the matching elements in the array, use the $filter in an aggregation as follows:要仅获取数组中的匹配元素,请按如下方式在聚合中使用$filter :
db.test.aggregate( [
{
$project: {
"workflowState.links": {
$filter: {
input: "$workflowState.links",
as: "link",
cond: {
$or: [
{ $eq: [ "$$link.from.nodeId", "NecHqBJvxk" ] },
{ $eq: [ "$$link.to.nodeId", "NecHqBJvxk" ] }
]
}
}
}
}
}
] )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.