2014-01-24 2 views
0

개체 배열이 있고 MongoDB 컬렉션에서 개체 배열에있는 개체와 일치하는 요소가있는 문서를 쿼리하고 싶습니다. 예를 들어Mongo DB : 일치 항목 수에 따른 정렬

는 :

var objects = ["52d58496e0dca1c710d9bfdd", "52d58da5e0dca1c710d9bfde", "52d91cd69188818e3964917b"]; 

db.scook.recipes.find({products: { $in: objects }} 

그러나, 나는 MongoDB의에서 일치의 수에 의해 결과를 정렬 할 수 있는지 알고 싶습니다.

예를 들어, 상단에는 정확하게 세 요소가 일치하는 "제조법"이 있습니다 : ["52d58496e0dca1c710d9bfdd", "52d58da5e0dca1c710d9bfde", "52d91cd69188818e3964917b"]. 즉 ["52d58496e0dca1c710d9bfdd", "52d58da5e0dca1c710d9bfde"], 단 하나의 세 번째 :

선택한 두 번째

두 가지 조리법이있다 즉 ["52d58496e0dca1c710d9bfdd"]

당신이 한 항목의 수를 얻을 수 있다면 그것은 좋은 것입니다.

+0

여기에는 MongoDB Aggregation Framework, MongoDB Map-Reduce 및 서버의 데이터 조작과 같은 세 가지 옵션이 있다고 생각합니다. 시간이 있다면, 나는 예를 들어 대답하려고 노력할 것이다. – EmptyArsenal

답변

0

집계 프레임 워크를 사용하면 다음 MongoDB 쿼리에서 필요한 것을 얻을 수 있어야한다고 생각합니다. 그러나 Mongoose를 사용하고 있다면 Mongoose 쿼리로 변환해야합니다. 나는 이것이 정확하게 작동 할 것이라는 확신이 없으므로, 제대로하기 위해 약간 놀아야 할 수도 있습니다. 또한이 대답은 $project 연산자 안에 $or 연산자를 사용할 수 있는지 여부와 true를 반환하는지 여부에 달려 있습니다. 그래도 작동하지 않는다면 map-reduce를 사용하여 필요한 것을 얻거나 서버 측에서 수행해야합니다.

db.recipes.aggregate(
    // look for matches 
    { $match : { products : { $or : objects }}}, 
    // break apart documents to by the products subdocuments 
    { $unwind : "$products" }, 
    // search for matches in the sub documents and add productMatch if a match is found 
    { $project : { 
     desiredField1 : 1, 
     desiredField2 : 1, 
     products : 1, 
     // this may not be a valid comparison, but should hopefully 
     // be true or 1 if there is a match 
     productMatch : { "$products" : { $or : objects }} 
    }}, 
    // group the unwound documents back together by _id 
    { $group : { 
     _id : "$_id", 
     products : { $push : "$products" }, 
     // count the matched objects 
     numMatches : { $sum : "$productMatch" }, 
     // increment by 1 for each product 
     numProducts : { $sum : 1 } 
    }}, 
    // sort by descending order by numMatches 
    { $sort : { numMatches : -1 }} 
)