【发布时间】:2014-11-07 03:50:09
【问题描述】:
假设我在 mongodb 中有一个集合,其对象有一个嵌套数组。我想根据数组中特定元素的值进行排序。这可能吗?
例如(我刚刚制作了示例),如果我有一组电影类型(动作、喜剧、浪漫)和用户提交的示例,我能否找到给定用户提交的所有对象,按日期排序电影?
例如,我想查找“Aaron”提交示例的所有类型,按“Aaron”提交示例的年份排序。
这几乎就像排序中的需要 where 子句。
> db.movies.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.movies.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"
}
]
}
请注意,返回的文档是按收藏年份排序的(如预期的那样)——有什么方法可以仅按给定用户提交的文档排序?对于一些额外的细节,我正在为 nodejs 使用 node-native mongo 驱动程序。
【问题讨论】: