2016-04-26 148 views
1

我正在使用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

您需要向我們展示了與樣本文件預期的結果,而不僅僅是你得到的結果。 – styvane

+0

@ user3100115檢查更新的問題 –

回答

3

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

但這是低效率的,如果你想要的是那種你的數組,你絕對不應該這樣做。


你可以使用.sortsorted功能總是這樣做客戶端。

1

如果你不想更新,但只得到文件,可以使用下面的查詢

db.test.aggregate(
[ 
    {$unwind : "$topics"}, 
    {$sort : {"topics.weight":-1}}, 
    {"$group": {"_id": "$_id", "topics": {"$push": "$topics"}}} 
] 
) 
+0

添加'{「$ match」:{「_id」:「12345」}},'用於管道參數吐出正是我想要的! –

+0

@BediE你有沒有注意到這是我的答案的副本,並沒有增加任何價值的現有的? – styvane

0

它爲我的作品:

db.getCollection('mycollection').aggregate(
{$project:{topics:1}}, 
{$unwind:"$topics"}, 
{$sort :{"topics.words":1}}) 
+0

這是錯誤的,它不會給出預期的結果。 – styvane

相關問題