MongoDB 在其他文档中按 属性 排序

MongoDB sort by property in other document

为了扩展我的 node.js 应用程序的 JSON-API 功能,我试图根据关系(又名其他文档)对查询进行排序,尽管我不想 return 他们。

根据 JSON-API documentation:

a sort field of author.name could be used to request that the primary data be sorted based upon the name attribute of the author relationship.

例如db.collection('books').find({}) returns:

[
    {
        type: "book",
        id: "2349",
        attributes: {
            title: "My Sweet Book"
        },
        relationships: {
            author: {
                data: {
                    type: "authors",
                    id: "9"
                }
            }
        }
    },
    {} // etc ...
]

db.collection('authors').find({id: "9"}) returns:

[
    {
        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}},
])

注释

您可以尝试以下聚合。

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