2017-03-10 65 views
0

爲了擴展我的node.js應用程序的JSON-API功能,我試圖根據關係(也稱爲其他文檔)對查詢進行排序,儘管我不想返回它們。MongoDB按其他文檔中的屬性排序

按照JSON-API documentation

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數據的全局函數。
    • 這意味着我們不知道閹排序關鍵字是attributerelationship
  • 大多數服務器上運行的LTS版本,並有MongoDB的3.2

回答

1

你可以試試下面聚集。

$lookup加入到authors集合,然後$unwind拼合book_author陣列用於應用$sortname場和$project與排斥,除去book_author場(僅適用起始蒙戈3.4版本)。對於較低版本,您必須包含您想要保留的所有其他字段,並在$project階段排除book_author字段。

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

看起來很有希望。現在上傳。我們可以(1)「放鬆」到一個點(在這種情況下是1)嗎? – Redsandro

+0

對不起,我不明白你對'$ unwind'的評論。對於文章中提到的編輯,您可以在'$ unwind'階段之後在'$ project'階段添加一個字段,類似於'sortkey:{$ ifNull:[「$ attribute」,「relationship」]}'',之後是''sort'''sortkey':-1'。讓我知道你的想法。 「 – Veeram

+0

_」對不起,我不明白你對$ unwind的評論「_ 我們可以'只展開數組的第一個_n_條目嗎? – Redsandro