【发布时间】:2017-03-10 12:28:49
【问题描述】:
为了扩展我的 node.js 应用程序的 JSON-API 功能,我正在尝试根据关系(也称为其他文档)对查询进行排序,尽管我不想返回它们。
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
【问题讨论】:
标签: node.js mongodb sorting json-api