2017-03-10 3 views
0

node.js 응용 프로그램의 JSON-API 기능을 확장하기 위해 관계를 기반으로 쿼리를 정렬하려고합니다 (일명 다른 문서). 반환하지는 않지만 . JSON-API documentation 따르면MongoDB 다른 문서의 속성으로 정렬

는 :

author.name의 정렬 필드는 주 데이터가 author 관계 name 속성에 기초하여 정렬되도록 요청하는데 사용될 수있다.

예 : db.collection('books').find({}) 반환 :

[ 
    { 
     type: "book", 
     id: "2349", 
     attributes: { 
      title: "My Sweet Book" 
     }, 
     relationships: { 
      author: { 
       data: { 
        type: "authors", 
        id: "9" 
       } 
      } 
     } 
    }, 
    {} // etc ... 
] 

db.collection('authors').find({id: "9"}) 반환 :
db.collection('books').find({}).sort({"author.name": -1})

가 나는 집계에 쿼리를 변환 할 필요가 있다고 생각 :

[ 
    { 
     type: "author", 
     id: "9", 
     attributes: { 
      name: "Hank Moody" 
     } 
    } 
] 

는 지금은 예를 들어, 비슷한 일을 할 수있는 방법이 필요합니다 그래서 나는 $lookup 연산자를 사용할 수 있지만, localFieldforeignField을 어떻게 사용하는지 모르겠습니다.

db.collection('books').aggregate([ 
    {$match: {}}, 
    {$lookup: {from: "authors", localField: "attributes.author.data.id", foreignField: "id", as: "temp.author"}}, 
    {$sort: {"$books.temp.author.name": -1}}, 
    {$project: {temp: false}}, 
]) 

참고

  • 이 JSON-API의 데이터를 가져 오는위한 글로벌 함수가 될 것입니다. 정렬 키가 attribute 또는 relationship입니다 어떠했는지
    • 이 의미 우리는을 모른다.
  • 대부분의 서버는 LTS 버전을 실행하고 집계 아래 시도 할 수 MongoDB를 3.2

답변

1

있습니다.

$lookup

은 (단지 몽고 3.4 버전을 시작할 작동) book_author 필드를 제거하여 제외 name 필드 $sort$project을인가하는 book_author 배열을 평탄화 $unwind 하였다 authors 컬렉션에 참여한다. 더 낮은 버전의 경우 유지하고자하는 다른 모든 필드를 포함하고 book_author 필드는 $project 단계에서 제외해야합니다.

db.collection('books').aggregate([{ 
    $lookup: { 
     from: "authors", 
     localField: "relationships.author.data.id", 
     foreignField: "id", 
     as: "book_author" 
    } 
}, { 
    $unwind: "$book_author" 
}, { 
    $sort: { 
     "book_author.attributes.name": -1 
    } 
}, { 
    $project: { 
     "book_author": 0 
    } 
}]) 
+0

유망 해 보인다. Upvoted for now. 우리는 (1)'$ unwind '를 (이 경우 1)까지 할 수 있습니까? – Redsandro

+0

죄송합니다.'$ unwind'에 대한 귀하의 의견을 이해하지 못했습니다. 게시물에서 언급 한 편집을 위해'$ project' 단계에서'sortkey : {$ ifNull : [ "$ attribute", "relationship"]}''$ unwind' 단계 다음에 필드를 추가 할 수 있습니다. ''sortkey ": -1로'$ sort'를 실행하십시오. 당신이 무슨 생각을하는지 제게 알려주세요. – Veeram

+0

_ "$ unwind에 대한 귀하의 의견을 이해하지 못했습니다"_ 배열의 첫 번째 _n_ 항목 만'$ unwind '할 수 있습니까? – Redsandro