如何将选定的字段值添加为$ group参数中的新字段

时间:2015-07-29 17:12:24

标签: mongodb mongoose

我一直在尝试将两个文档合并到一个结果文档中。虽然我尝试了$group$project运算符,但我不能。

我的示例集合如下;

{
    "_id"  : "55b87567c022bab41a89a477",
    "type" : "armchair",
    "price": 44.12
},
{
    "_id"  : "55b87567c022bab41a89a488",
    "type" : "table",
    "price": 86.00
},
{
    "_id"  : "55b87567c022bab41a89a499",
    "type" : "LCD TV",
    "price": 550.00
}

我的代码;

Price.aggregate([
            { 
                $match: {
                    $and: [
                        { $or: [{ 'type': 'armchair' }, {'type':'table'}] }
                    ] 
                }
            }, 
            //{
            //  $group: {
            //      _id: 0, 
            //      armchairPrice: {$cond: { if: { $eq: [ "$type", "armchair" ] }, then: "$price", else: null }},
            //      tablePrice: {$cond: { if: { $eq: [ "$type", "table" ] }, then: "$price", else: null }}
            //  }
            //}, 
            {
                $project: {
                    _id: 0, 
                    armchairPrice: {$cond: { if: { $eq: [ "$type", "armchair" ] }, then: "$price", else: null }},
                    tablePrice: {$cond: { if: { $eq: [ "$type", "table" ] }, then: "$price", else: null }}
                }
            }
        ]   

我现在的结果;

[ { armchairPrice: 44.12, tablePrice: null },
  { armchairPrice: null, tablePrice: 86.00 } ]

但结果必须如下所示;

{
    "_id" : 0,
    "armchairPrice": 44.12,
    "tablePrice": 86.00
}

1 个答案:

答案 0 :(得分:1)

您的$group已关闭,但您需要使用accumulator运算符来识别管道中的哪个对象来提取每个价格。在这种情况下,$max可以解决问题,因为任何有效价格都大于null

Price.aggregate([
    { 
        $match: {
            $and: [
                { $or: [{ 'type': 'armchair' }, {'type':'table'}] }
            ] 
        }
    }, 
    {
      $group: {
          _id: 0, 
          armchairPrice: {$max: {$cond: { 
              if: { $eq: [ "$type", "armchair" ] }, 
              then: "$price", 
              else: null }}},
          tablePrice: {$max: {$cond: { 
              if: { $eq: [ "$type", "table" ] }, 
              then: "$price", 
              else: null }}}
      }
    }
])

结果:

[ {
    "_id" : 0,
    "armchairPrice" : 44.12,
    "tablePrice" : 86
 }