2017-01-24 5 views
0

私はmongodbに少し新しく、状況があります。

私のMongoDBのコレクション内のエントリは約300Kである、私は新しいと私のコードにすべての古いエントリを移行するためにMongoDB aggregateを使用し、私はサブストリング撮りたいということ、それを達成したい何

collection.aggregate([ 
    { $group: { 
    _id: "$_id", 
    "new_id" : {$substr : [{$first: "$old_id"}, 2,-1]}, //error exists here 
    "new_roles": {$push: "$old_role"}, 
    } 
    }, 
    { $out: newCollection} 
], {allowDiskUse:true}, function (updateError, updateResult) { 
    if (!updateError) { 
    return cb(false, true); 
    } else { 
    return cb(true, false); 
    } 
}) 

のように見えますold_idを入力してnew_idに入力します。古いコレクションのold_idはa-112a-34311のようになります。これらの古いIDからa-を削除して新しいIDに入れたいと思います。

上記のコードを試しましたが、エラーThe $substr accumulator is a unary operatorが表示されます。私はエラーを検索しようとしましたが運がありませんでした

答えて

1

$ substステージはアキュムレータ演算子ではないので、$ groupステージでは使用できません。次のような$ projectステージでこれを行う必要があります:

collection.aggregate([ 
    { $group: { 
    _id: "$_id", 
    "new_id" : {$first: "$old_id"}, 
    "new_roles": {$push: "$old_role"}, 
    } 
    }, 
    {$project: { 
     "new_id": {$substr: ["$new_id", 2, -1]}, 
     "new_roles": 1 
    } 
    }, 
    { $out: newCollection} 
], {allowDiskUse:true}, function (updateError, updateResult) { 
    if (!updateError) { 
    return cb(false, true); 
    } else { 
    return cb(true, false); 
    } 
})