主要收集文档包含工作流程详细信息。每个工作流程都有详细信息,其中有一个工作流程状态对象,并且链接中包含一组对象。
当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
}
我已经尝试过该查询
db.collection.find({
"workflowState.links": {
$elemMatch: {
"from.nodeId": "NecHqBJvxk"
}
}
},
{
"workflowState.links.$": 1
})
但它仅返回数组中的第一个匹配项。
我希望这种格式的输出。
{
"_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"
}
]
}
}
如何从匹配条件的数组中获取对象的所有元素?
预先感谢
答案 0 :(得分:1)
在$ unwind阶段使用Aggregate函数
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",
}
}
]);
答案 1 :(得分:0)
要仅获取数组中的匹配元素,请按如下所示在汇总中使用$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" ] }
]
}
}
}
}
}
] )