排除原始匹配的聚合匹配数组元素



我希望使用"链接"集合链接不同集合中的各种记录。 稍后,我想为给定对象查找它链接到的内容,但不包括给定的对象引用。 这是我到目前为止所拥有的:

链接集合:

{ "id" : 1, "vertices" : [ { "id" : 1, "type" : "node" }, { "id" : 1, "type" : "entity" } ] }
{ "id" : 2, "vertices" : [ { "id" : 2, "type" : "node" }, { "id" : 1, "type" : "entity" } ] }
{ "id" : 3, "vertices" : [ { "id" : 3, "type" : "node" }, { "id" : 2, "type" : "entity" } ] }
{ "id" : 4, "vertices" : [ { "id" : 1, "type" : "node" }, { "id" : 1, "type" : "alert" } ] }
{ "id" : 5, "vertices" : [ { "id" : 1, "type" : "node" }, { "id" : 2, "type" : "entity" } ] }
{ "id" : 6, "vertices" : [ { "id" : 1, "type" : "node" }, { "id": 2, "type": "node" } ] }

所以我的第一个想法是这样做:

db.link.aggregate([
{$match:{vertices:{$elemMatch:{id:1,type:"node"}}}},
{$unwind:"$vertices"}
]);

这会产生:

{ "_id" : ObjectId("598ccc382381d7587032747c"), "id" : 1, "vertices" : { "id" : 1, "type" : "node" } }
{ "_id" : ObjectId("598ccc382381d7587032747c"), "id" : 1, "vertices" : { "id" : 1, "type" : "entity" } }
{ "_id" : ObjectId("598cd0f421d830c187071aca"), "id" : 4, "vertices" : { "id" : 1, "type" : "node" } }
{ "_id" : ObjectId("598cd0f421d830c187071aca"), "id" : 4, "vertices" : { "id" : 1, "type" : "alert" } }
{ "_id" : ObjectId("598dd404228b6d88470ed052"), "id" : 5, "vertices" : { "id" : 1, "type" : "node" } }
{ "_id" : ObjectId("598dd404228b6d88470ed052"), "id" : 5, "vertices" : { "id" : 2, "type" : "entity" } }
{ "_id" : ObjectId("598e201d720b766ed9f1a496"), "id" : 6, "vertices" : { "id" : 1, "type" : "node" } }
{ "_id" : ObjectId("598e201d720b766ed9f1a496"), "id" : 6, "vertices" : { "id" : 2, "type" : "node" } }   

一个很好的开始,但我希望摆脱包含带有 { id:1 的顶点的行,类型:"节点"}。

因此,让我们向管道添加另一个$match:

db.link.aggregate([
{$match:{vertices:{$elemMatch:{id:1,type:"node"}}}},
{$unwind: "$vertices"},
{$match:{ 'vertices.id': {$ne:1}, 'vertices.type': {$ne:'node'} } }
]);

这会产生结果:

{ "_id" : ObjectId("598dd404228b6d88470ed052"), "id" : 5, "vertices" : { "id" : 2, "type" : "entity" } }

当我真正期望时:

{ "_id" : ObjectId("598ccc382381d7587032747c"), "id" : 1, "vertices" : { "id" : 1, "type" : "entity" } }
{ "_id" : ObjectId("598cd0f421d830c187071aca"), "id" : 4, "vertices" : { "id" : 1, "type" : "alert" } }
{ "_id" : ObjectId("598dd404228b6d88470ed052"), "id" : 5, "vertices" : { "id" : 2, "type" : "entity" } }
{ "_id" : ObjectId("598e201d720b766ed9f1a496"), "id" : 6, "vertices" : { "id" : 2, "type" : "node" } }

那么我在第二$match陈述中做错了什么?

逻辑再次出击! 对于其他人为此苦苦挣扎:

db.link.aggregate([
{$match:{vertices:{$elemMatch:{id:1,type:"node"}}}},
{$unwind: "$vertices"},
{$match:{$or: [
{'vertices.type':{$ne:'node'}},
{'vertices.id':{$ne:1}}
]}}
]);

给了我想要的结果。

最新更新