2017-03-10 8 views
0

私のnode.jsアプリケーションのJSON-API機能を拡張するために、私はそれらを返すことはしませんが、リレーションシップ(AKAの他のドキュメント)に基づいてクエリをソートしようとしています。 。 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"})リターン:

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

今、私は例えばに似た何かをするいくつかの方法が必要になります。
db.collection('books').find({}).sort({"author.name": -1})

私は私を集計にクエリを変換する必要があると思いますだから私は$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

を持っています。 (のみMongoの3.4バージョンを開始する動作)book_authorフィールドを除去するために排除しnameフィールドと$project$sortを適用するためのbook_authorアレイを平坦に$unwind続いauthorsコレクションに参加する

$lookup。下位バージョンの場合は、保持するフィールドをすべて含め、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。 (1) '$ unwind 'をポイント(この場合は1)までできるか? – Redsandro

+0

申し訳ありませんが、 '$ unwind'に対するあなたのコメントを理解できませんでした。この記事で言及されている編集のために、 '$ project'ステージにフィールドを追加することができます。これは、' $ unwind'ステージの後に 'sortkey:{$ ifNull:[" $ attribute "、" relationship "]}' '$ sort'を' 'sortkey":-1'で実行します。どう考えているか教えてください。 – Veeram

+0

_ "$ unwindであなたのコメントを理解できませんでした" _ 配列の最初の_n_エントリだけを '$ unwind 'できますか? – Redsandro

関連する問題