我可以通过Mongo中的嵌套数组中的元素进行sorting吗?

比方说,我有一个在MongoDB中的对象具有嵌套数组的集合。 我想基于数组的特定元素的值进行sorting。 这可能吗?

例如(我只是做了这个例子),如果我有一个电影types(动作,喜剧,浪漫)和用户提交的例子集合,我可以find所有对象提交给定的用户提交sorting的电影date?

例如,我想find“Aaron”提交示例的所有types,按“Aaron”示例的年份sorting。

它几乎就像一个需要在哪里的条款。

> 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" } ] } 

> 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" } ] } 

请注意,文档按照收集年份(按预期)进行sorting – 只有通过给定用户提交的文档才能进行sorting的任何方法? 对于一些额外的细节,我正在使用nodejs的节点本机mongo驱动程序。

…任何方式来sorting只是由一个给定的用户提交的?

我不认为这会按照你想要的方式运作。

在MongoDB中,查询返回整个文档。 当您执行以下查询时,您正在查找提交者与'Aaron'匹配'Aaron'所有文档。

 > db.movies.find({'examples.submitter': 'Aaron'}) 

请注意, 'Aaron'理论上可以在同一个文档中匹配两次,但只返回一次该文档。 这使分拣问题变得复杂。

 > db.movies.find({'examples.submitter': 'Aaron'}).sort({'examples.year': 1}) 

那么当一个文件包含'Aaron'不同年份的两个东西时,你期望什么? 请记住,我们只能sorting文件,我们不能用查询sorting内部数组。

这里的问题是你使用的“对象数组”,这使整个过程变得复杂。 你的sorting问题假设我们可以对内部对象进行操作,而我们实际上不能。

请看看可能提供你正在寻找的新的聚合框架 。 请注意,这是当前不稳定分支中的一项function。

如果其他人绊倒在这,我能够通过创build索引来解决类似的问题:

 {'examples.submitter': 1, 'examples.year': 1} 

如果您强制查询使用此索引使用提示(“indexname”),您的结果将按索引的顺序回来。

对于你的情况,你将不得不使用eval并在服务器端进行自定义sorting。 看看这里的sorting的具体例子。 你的比较函数会稍微复杂一点,因为你必须通过“examples”数组并且通过提交者进行过滤。