【问题标题】:MongoDB sort by property in other documentMongoDB按其他文档中的属性排序
【发布时间】:2017-03-10 12:28:49
【问题描述】:

为了扩展我的 node.js 应用程序的 JSON-API 功能,我正在尝试根据关系(也称为其他文档)对查询进行排序,尽管我不想返回它们。

根据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 数据的全局函数。
    • 这意味着我们不知道排序键是attribute 还是relationship
  • 大多数服务器运行 LTS 版本并具有 MongoDB 3.2

【问题讨论】:

    标签: node.js mongodb sorting json-api


    【解决方案1】:

    您可以尝试以下聚合。

    $lookup 加入 authors 集合,然后是 $unwind 以展平 book_author 数组,以便在 name 字段和 $project 上应用 $sort,排除删除 book_author 字段(仅适用开始 Mongo 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
        }
     }])
    

    【讨论】:

    • 看起来很有希望。暂时赞成。我们可以 (1) $unwind 到一个点(在这种情况下为 1)吗?
    • 对不起,我不明白您对$unwind 的评论。对于帖子中提到的编辑,您可以在$project 阶段添加一个字段,例如sortkey: { $ifNull: [ "$attribute", "relationship" ] }$unwind 阶段后跟$sort"sortkey": -1。让我知道你的想法。
    • “抱歉,我不明白您对 $unwind 的评论” 我们可以 $unwind 仅数组的前 n 个条目吗?
    • 不,我们不能,因为$unwind 采用字段路径而不是表达式。您可以在 $unwind$slice 之前添加 $project 阶段以选择第一个 n 元素。类似{$project:{"book_author":{"$slice":["$book_author", n"]}}}
    猜你喜欢
    • 2016-10-07
    • 1970-01-01
    • 2013-01-02
    • 2021-07-30
    • 2017-10-07
    • 2014-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多