簡體   English   中英

如何在$ group參數中將所選字段值添加為新字段

[英]How to add selected fields value as new fields in $group parameter

我一直試圖將兩個文檔合並為一個結果文檔。 盡管我嘗試了$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
}

您的$group接近,但是您需要使用累加器運算符來識別管道中要從中拉出每個價格的對象。 在這種情況下, $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
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM