2017-01-20 42 views
0

我正在使用貓鼬獲取數據庫中的值可以符合兩個條件使用$或。 我希望響應能被過濾器分開。

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

這是兩個單獨的查詢,所以你可以做他們分開,然後結合的結果。性能方面它不會那麼糟糕,如果你的工作組在裝入內存,它們被編入索引:

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是這樣的:

{ 
    "_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 
    ] 
} 

欲瞭解更多有關$group,請閱讀MongoDB $group(aggregation) Documenatation