2017-08-11 94 views
0

我希望使用“链接”集合链接不同集合中的各种记录。稍后,我想为给定对象找到它链接的内容,但不包含给定对象ref。这是我到目前为止有:不包含原始匹配的聚合匹配数组元素

链接集合:

{ "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,type:“node”}。

因此,让我们添加另一个$匹配管道:

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" } } 

那么我就是我在第二个$匹配语句中做错了?

回答

0

逻辑罢工了!对于其他人的努力:

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

给了我想要的结果。