我使用MongoDB shell获取一些结果,有序。这是一个采样器,
{
"_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" : []
{
"_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字段对它们进行分组。有没有办法做到这一点?
答案 0 :(得分:5)
MongoDB没有提供开箱即用的方法,但有一种解决方法是更新文档并使用$sort
更新运算符对数组进行排序。
db.collection.update_many({}, {"$push": {"topics": {"$each": [], "$sort": {"weight": -1}}}})
您仍然可以使用.aggregate()
这样的方法:
db.collection.aggregate([
{"$unwind": "$topics"},
{"$sort": {"_id": 1, "topics.weight": -1}},
{"$group": {"_id": "$_id", "topics": {"$push": "$topics"}}}
])
但是,如果您想要的只是对阵列进行排序,那么效率就会降低,而且您绝对不应该这样做。
答案 1 :(得分:1)
如果您不想更新但只获取文档,则可以使用以下查询
db.test.aggregate(
[
{$unwind : "$topics"},
{$sort : {"topics.weight":-1}},
{"$group": {"_id": "$_id", "topics": {"$push": "$topics"}}}
]
)
答案 2 :(得分:0)
它对我有用:
db.getCollection('mycollection').aggregate(
{$project:{topics:1}},
{$unwind:"$topics"},
{$sort :{"topics.words":1}})