我希望按持有最低foo.bar
值(即数组对象)的顺序返回文档。
我可以执行db.collection.find().sort({foo.0.bar: 1})
,但这只匹配数组中的第一个元素-正如您在下面的示例中看到的那样,将首先对项目1进行排序(foo.0.bar = 5),而我希望首先返回项目2,因为它具有最低值的对象。(foo.2.bar = 4)
=5。
{
"name": "Item 1",
"foo": [
{
"bar": 5
},
{
"bar": 6
},
{
"bar": 7
}
]
}
{
"name": "item 2",
"foo": [
{
"bar": 6
},
{
"bar": 5
},
{
"bar": 4
}
]
}
发布于 2011-03-16 04:22:58
使用map/reduce的另一种方法是将数组中的最小值存储为文档中的单独字段,然后可以对其进行排序。添加到数组时,如果新值低于当前记录的最小值,则还会更新此字段。
例如,你的第一个文档将变成这样(注意"minbar添加“):
{
"name": "Item 1",
"minbar" : 5,
"foo": [
{
"bar": 5,
}
{
"bar": 6,
}
{
"bar": 7,
}
]
}
发布于 2012-11-20 20:02:42
您可以使用mongo版本2.2中的aggregate命令执行这样的排序:
db.collection.aggregate([{$unwind: "$foo"},
{$project: {bars:"$foo.bar"}},
{$group: {_id:"$_id",min:{$min: "$bars"}}},
{$sort: {min:1}}])
发布于 2011-03-16 02:59:02
在mongo中没有直接的方法可以做到这一点。您需要使用map/reduce来检索每个数组中的最小值,然后按该最小值进行排序
https://stackoverflow.com/questions/5315658
复制相似问题