2017-01-20 1 views
0

私はmongooseを使用して、$またはを使用して2つの条件に対応するDBの値を取得しています。 私は応答をフィルタで区切りたいと思っています。

Cars.find({$or : [{color: 'blue'}, {color: 'red'}]}, function(Cars){ 
    console.log(Cars); 
}) 

このコードが返されます:

[ 
{ 
    _id: 'Car1', 
    color: 'blue' 
}, 
{ 
    _id: 'Car2', 
    color: 'red' 
}, 
] 

あなたは、各条件に対応するオブジェクトを知るのいずれかの方法を持っていますか?オブジェクト内の直接の比較を実現することなく。このような

:あなたがちょうどそれらを別々に行い、その結果を組み合わせることができますので、

[ 
    [ //Array with objects with color = 'blue' 
    { 
     _id: 'Car1', 
     color: 'blue' 
    }, 
    ], 
    [ //Array with objects with color = 'red' 
    { 
     _id: 'Car2', 
     color: 'red' 
    }, 
    ], 
] 
+0

あなたは 'CArSchema'を表示することができます –

答えて

0

は、あなたの出力は次のようになりますaggregateクエリ

Cars.aggregate([ 
    {$match:{color:{$in:['red','blue']}}}, 
    {$group:{_id:"$color",result: { $push: "$$ROOT" }}}, 
    {$project:{result:1,_id:0}} 
    ], function(err, cars){ 
     if(err) { 
      console.log(err); 
      // return error 
     } 
     console.log(cars); 
     // return success data 
}); 

で試すことができます:

[ 
    { 
    "result" : [ 
     { 
      "_id" : "Car1", 
      "color" : "blue" 
     }, 
     { 
      "_id" : "Car3", 
      "color" : "blue" 
     } 
    ] 
}, 
{ 
    "result" : [ 
     { 
      "_id" : "Car2", 
      "color" : "red" 
     } 
    ] 
} 
] 
0

これらは、2つの独立したクエリです。

const colors = [{color: 'blue'}, {color: 'red'}]; 
Promise.all(colors.map(color => Cars.find({ color }).then())) 
    .then(result => { 
    console.log('This is what you wanted:', result); 
    }); 
0

は、私はあなたがこのために$groupaggregate演算子を使用することができると思う:あなたのワーキングセットがメモリに適合し、それらがインデックス化されている場合、パフォーマンスは賢明なことは、それほど悪いことではないでしょう。

Cars.aggregate(
    [ 
     { $group : { _id : "$color", cars: { $push: "$$root" } } } 
    ] 
); 

これは、このようなresult何か得られます:$groupの詳細については

{ 
    "_id" : "red", 
    "cars" ://array of red color cars 
    [ 
     { "_id" : "car2", "color" : "red"},//if other fields are present, that too 
     { "_id" : "car4", "color" : "red" }//...and so on 
    ] 
} 

{ 
    "_id" : "blue", 
    "cars" ://array of blue color cars 
    [ 
     { "_id" : "car1", "color" : "blue"}, 
     { "_id" : "car2", "color" : "blue" }//...and so on 
    ] 
} 

を、MongoDB $group(aggregation) Documenatationをお読みください。

関連する問題