我可以按Mongo中嵌套数组中的元素排序吗?

Zug*_*alt 5 mongodb node.js

假设我在mongodb中有一个集合,其对象有一个嵌套数组.我想根据数组的特定元素的值进行排序.这可能吗?

例如(我刚刚做了一个例子),如果我有一组电影类型(动作,喜剧,浪漫)和用户提交的例子,我能否找到按电影日期排序的给定用户提交的所有对象?

例如,我想找到"Aaron"提交示例的所有类型,按照"Aaron"提交的示例年份排序.

它几乎就像需要where where子句一样.

> db.movi​​es.find().pretty();

{
    "_id" : ObjectId("4f2f07c1ec2cb81a269362c6"),
    "type" : "action",
    "examples" : [
        {
            "title" : "Gladiator",
            "year" : 2000,
            "submitter" : "Aaron"
        },
        {
            "title" : "Mission Impossiple",
            "year" : 1996,
            "submitter" : "Bill"
        },
        {
            "title" : "The Terminator",
            "year" : 1984,
            "submitter" : "Jane"
        }
    ]
}
{
    "_id" : ObjectId("4f2f07edaee5d897ea09f511"),
    "type" : "comedy",
    "examples" : [
        {
            "title" : "The Hangover",
            "year" : 2009,
            "submitter" : "Aaron"
        },
        {
            "title" : "Dogma",
            "year" : 1999,
            "submitter" : "Bill"
        },
        {
            "tile" : "Airplane",
            "year" : 1980,
            "submitter" : "Jane"
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

> db.movi​​es.find({'examples.submitter':'Aaron'}).sort({'examples.year':1}).pretty();

{
    "_id" : ObjectId("4f2f07edaee5d897ea09f511"),
    "type" : "comedy",
    "examples" : [
        {
            "title" : "The Hangover",
            "year" : 2009,
            "submitter" : "Aaron"
        },
        {
            "title" : "Dogma",
            "year" : 1999,
            "submitter" : "Bill"
        },
        {
            "tile" : "Airplane",
            "year" : 1980,
            "submitter" : "Jane"
        }
    ]
}
{
    "_id" : ObjectId("4f2f07c1ec2cb81a269362c6"),
    "type" : "action",
    "examples" : [
        {
            "title" : "Gladiator",
            "year" : 2000,
            "submitter" : "Aaron"
        },
        {
            "title" : "Mission Impossiple",
            "year" : 1996,
            "submitter" : "Bill"
        },
        {
            "title" : "The Terminator",
            "year" : 1984,
            "submitter" : "Jane"
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

请注意,文档按收集年份(按预期)排序返回 - 是否可以按给定用户提交的方式进行排序?对于一些额外的细节我使用nodejs的node-native mongo驱动程序.

Gat*_* VP 5

...任何方式只按给定用户提交的方式进行排序?

我不认为这会按照你想要的方式解决.

在MongoDB中,查询返回整个文档.执行以下查询时,您将查找任何提交者匹配的所有文档'Aaron'.

> db.movies.find({'examples.submitter': 'Aaron'})
Run Code Online (Sandbox Code Playgroud)

请注意,'Aaron'理论上可以在同一文档中匹配两次,但只返回该文档一次.这使排序问题复杂化.

> db.movies.find({'examples.submitter': 'Aaron'}).sort({'examples.year': 1})
Run Code Online (Sandbox Code Playgroud)

那么当一个文档包含两个'Aaron'不同年份的东西时,您期望什么?请记住,我们只能对文档进行排序,我们无法使用查询对内部数组进行排序.

这里的问题是你正在使用"对象数组",这使整个过程变得复杂.你的排序问题假设我们可以对内部对象采取行动而我们实际上不能.

请查看新的聚合框架,它可能会提供您正在寻找的内容.请注意,这是不稳定分支中的一个功能.