如何在数组字段中对子文档进行排序? [英] How to sort sub-documents in the array field?
问题描述
我正在使用MongoDB Shell来获取一些结果,命令.这是一个采样器,
I'm using the MongoDB shell to fetch some results, ordered. Here's a sampler,
{
"_id" : "32022",
"topics" : [
{
"weight" : 281.58551703724993,
"words" : "some words"
},
{
"weight" : 286.6695125796183,
"words" : "some more words"
},
{
"weight" : 289.8354232846977,
"words" : "wowz even more wordz"
},
{
"weight" : 305.70093587160807,
"words" : "WORDZ"
}]
}
我想要得到的是相同的结构,但按"topics" : []
what I want to get is, same structure, but ordered by "topics" : []
{
"_id" : "32022",
"topics" : [
{
"weight" : 305.70093587160807,
"words" : "WORDZ"
},
{
"weight" : 289.8354232846977,
"words" : "wowz even more wordz"
},
{
"weight" : 286.6695125796183,
"words" : "some more words"
},
{
"weight" : 281.58551703724993,
"words" : "some words"
},
]
}
我设法获得了一些有序的结果,但是按ID字段对它们进行分组没有运气.有办法吗?
I managed to get some ordered results, but no luck in grouping them by id field. is there a way to do this?
推荐答案
MongoDB没有提供开箱即用的方法,但是有一种解决方法是更新您的文档并使用
MongoDB doesn't provide a way to do this out of the box but there is a workaround which is to update your documents and use the $sort
update operator to sort your array.
db.collection.update_many({}, {"$push": {"topics": {"$each": [], "$sort": {"weight": -1}}}})
您仍然可以像这样使用.aggregate()
方法:
You can still use the .aggregate()
method like this:
db.collection.aggregate([
{"$unwind": "$topics"},
{"$sort": {"_id": 1, "topics.weight": -1}},
{"$group": {"_id": "$_id", "topics": {"$push": "$topics"}}}
])
但是,如果您只想对数组进行排序,则效率会降低,并且您绝对不应该这样做.
But this is less efficient if all you want is sort your array, and you definitely shouldn't do that.
You could always do this client side using the .sort
or sorted
function.
这篇关于如何在数组字段中对子文档进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!