爲了擴展我的node.js
應用程序的JSON-API功能,我試圖根據關係(也稱爲其他文檔)對查詢進行排序,儘管我不想返回它們。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
運營商,但我不知道如何使用localField
和foreignField
。
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)「放鬆」到一個點(在這種情況下是1)嗎? – Redsandro
對不起,我不明白你對'$ unwind'的評論。對於文章中提到的編輯,您可以在'$ unwind'階段之後在'$ project'階段添加一個字段,類似於'sortkey:{$ ifNull:[「$ attribute」,「relationship」]}'',之後是''sort'''sortkey':-1'。讓我知道你的想法。 「 – Veeram
_」對不起,我不明白你對$ unwind的評論「_ 我們可以'只展開數組的第一個_n_條目嗎? – Redsandro