2017-01-16 3 views
1

集計では、object(which is an array)が存在します。これは、position 7 inside an arrayに存在します。例えば、私は["$_id", "$coupon_type", "$nonce", "$total_coupons", "$amount", "$curr_ctr", "$coupon_codes", { indexes: conditions}]としての私の結果を投影しますcoupon_type: 0ためだから今mongoDB集約で配列内の位置にオブジェクトを表示する

{ 
     "$project": { 
      "result": { 
       "$cond": { 
        "if": { 
         "$eq": ["$coupon_type", 1] 
        }, 
        "then": ["$_id", "$coupon_type", "$nonce", "$total_coupons", "$amount", "$curr_ctr"], 
        "else": ["$_id", "$coupon_type", "$nonce", "$total_coupons", "$amount", "$curr_ctr", "$coupon_codes", { 
         indexes: conditions 
        }] 
       } 
      } 
     } 
    }, 
    { 
     "$project": { 
      obj: { $arrayElemAt: [ "$result", 7 ] } // here how to project indexes. 

    } 

以下のような分野を持っています。

今私の次のパイプラインでプロジェクトしたいフィールドは 'indexes'なので、私は$arrayElemAt: [ "$result", 7 ]と書いてみましたが、これは7番目のインデックス要素を与えていますが、この7番目の位置にオブジェクト 'indexes'

私はこのようなものを書いています。$arrayElemAt: [ "$result", 7 ].indexesこれは、abjectを指す正しい方法ではありません。

どうすればいいですか?

答えて

1

あなたは、プロジェクトのステージを組み合わせて、指標を投影する$letを使用することができます。

$project: { 
    indexes: { 
     $let: { 
      vars: { 
       obj: { 
        $arrayElemAt: [{ 
         "$cond": { 
          "if": { 
           "$eq": ["$coupon_type", 1] 
          }, 
          "then": ["$_id", "$coupon_type", "$nonce", "$total_coupons", "$amount", "$curr_ctr"], 
          "else": ["$_id", "$coupon_type", "$nonce", "$total_coupons", "$amount", "$curr_ctr", "$coupon_codes", { 
           indexes: conditions 
          }] 
         } 
        }, 7] 
       } 
      }, 
      in: "$$obj.indexes" 
     } 
    } 
} 
+0

実際には申し訳ありませんが、コード全体をアップロードしていないので、coupon_type 1の7番目のインデックスが存在しないため、coupon_typeが0に等しい場合のみobjを投影します。しかし、あなたのコードに応じても、あなたはobj.indexesをプロジェクトしようとしますので、あなたのコードでそれを変更してくださいできますか? –

+0

私は何も変えなかった。 2番目のプロジェクトのコードでも同じことが行われています。 2番目のプロジェクトにコードを移動し、$ letを使用してインデックスを抽出することができます。それはあなたが欲しいものですか? – Veeram

+0

あなたはちょうど私が1つのことを言うことができます私は単一の投影で3つの操作を実行したいと思う今私は$ letを実行するために使用することができます、その後、私の問題は完全に解決されます。私は3回$を使うことを考えましたが、それはうまくいくとは思いません。また、私はここに男の助けてくれてありがとう:) –

1

あなたは、2番目の$プロジェクト段階を追加することによって、これを達成することができます

db.collection.aggregate([{ 
      "$project": { 
       "result": { 
        "$cond": { 
         "if": { 
          "$eq": ["$coupon_type", 1] 
         }, 
         "then": ["$_id", "$coupon_type", "$nonce", "$total_coupons", "$amount", "$curr_ctr"], 
         "else": ["$_id", "$coupon_type", "$nonce", "$total_coupons", "$amount", "$curr_ctr", "$coupon_codes", { 
          indexes: conditions 
         }] 
        } 
       } 
      } 
     }, 
     { 
      "$project": { 
       obj: { $arrayElemAt: [ "$result", 7 ] } 

     }, 
     {"$project": { 
       obj: "$obj.indexes" } 
     } 
]) 
関連する問題