2016-07-21 54 views
0

下面的代码首先在一个字段上连接两个集合,并尝试过滤其他字段上的值。

db.zeroDimFacts.aggregate(
{$lookup:{from:"zeroDim",localField:"Kind",foreignField:"Model", as:"EmbedUp"}}, 
{$project: {"EmSub":"$EmbedUp.Sub","Result": {$eq:["$Type","$EmbedUp.Sub"]}, "type":"$Type"}}) 

请检查以下输出的代码。即使'EmSub'&'$ Type'具有相同的值,但它不会显示在“结果”字段中。 如果是因为'EmSub'显示为数组,我如何比较只包含该数组中的值?

/* 1 */ 
{ 
    "_id" : NumberLong(1), 
    "EmSub" : [ 
     "Fruit" 
    ], 
    "Result" : false, 
    "type" : "Fruit" 
} 

/* 2 */ 
{ 
    "_id" : NumberLong(2), 
    "EmSub" : [ 
     "Fruit" 
    ], 
    "Result" : false, 
    "type" : "Fruit" 
} 

/* 3 */ 
{ 
    "_id" : NumberLong(3), 
    "EmSub" : [ 
     "Fruit" 
    ], 
    "Result" : false, 
    "type" : "Fruit" 
} 
+0

尽量$ EQ: “$类型”, “$ EmbedUp.Sub $。”] –

+0

@AmiramKorach:得到下面的错误: 断言:命令失败:{ \t“ok”:0, \t“errmsg”:“FieldPath字段名称可能不以'$'开头。”, \t“code”:16410 }:聚合失败 –

+0

对不起。尝试:“EmSub”:{$ first:“$ EmbedUp.Sub”}和比较$ eq:[“$ Type”,{$ first:“$ EmbedUp.Sub”}] –

回答

0

您可以放松身心的阵列与它的元素这样的比较:

db.zeroDimFacts.aggregate([{$lookup:{from:"zeroDim",localField:"Kind",foreignField:"Model", as:"EmbedUp"}}, 
{$unwind: "$EmbedUp"}, 
{$project: {"EmSub":"$EmbedUp.Sub","Result": {$eq:["$Type","$EmbedUp.Sub"]}, "type":"$Type"}}]);

它可以再给你一个以上的结果对于单个zeroDimFacts _id,但是你可以将它们

db.zeroDimFacts.aggregate([{$lookup:{from:"zeroDim",localField:"Kind",foreignField:"Model", as:"EmbedUp"}}, 
{$unwind: "$EmbedUp"}, 
{$project: {"EmSub":"$EmbedUp.Sub","Result": {$eq:["$Type","$EmbedUp.Sub"]}, "type":"$Type"}}, 
{$group: {_id: "$_id", EmSub: {$push: "$EmSub"}, Result: {$push: "$Result"}, type: {$push: "$type"}}}]);