mongodb:无法从$ project和$ eq获取结果

时间:2016-07-21 09:26:43

标签: mongodb

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

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

请检查下面的代码输出。即使' EmSub' &安培; ' $类型'具有相同的价值,它没有显示在'结果'领域。 如果是因为' 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"
}

1 个答案:

答案 0 :(得分: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"}}}]);