這是我的示例資料,我有一個 userId 和一個陣列“watchHistory”,“watchHistory”陣列包含用戶觀看的視頻串列:
{
"_id": "62821344445c30b35b441f11",
"userId": 579,
"__v": 0,
"watchHistory": [
{
"seenTime": "2022-05-23T08:29:19.781Z",
"videoId": 789456,
"uploadTime": "2022-03-29T12:33:35.312Z",
"description": "Biography of Indira Gandhi",
"speaker": "andrews",
"title": "Indira Gandhi",
"_id": "628b45df775e3973f3a670ec"
},
{
"seenTime": "2022-05-23T08:29:39.867Z",
"videoId": 789455,
"uploadTime": "2022-03-31T07:37:39.712Z",
"description": "What are some healthy food habits to stay healthy",
"speaker": "morris",
"title": "Healthy Food Habits",
"_id": "628b45f3775e3973f3a670"
},
]
}
我需要匹配 userId,然后我需要使用“watchHistory.seenTime”對其進行排序,seenTime 欄位指示用戶何時看到視頻。所以我需要排序,就像最后觀看的視頻應該排在串列的首位。我沒有使用 unwind 的權限,所以任何人都可以幫助我。謝謝你。
uj5u.com熱心網友回復:
如果您使用的是 MongoDB 5.2 及更高版本,則可以$sortArray在聚合管道中使用運算子。您的管道應如下所示:
db.collection.aggregate(
[
{"$match":
{ _id: '62821344445c30b35b441f11' }
},
{
"$project": {
_id: 1,
"userId": 1,
"__v": 1,
"watchHistory": {
"$sortArray": { input: "$watchHistory", sortBy: { seenTime: -1 }}
}
}
}
]
);
請根據您需要過濾的鍵和值修改“$match”階段的過濾器。這是檔案的鏈接。
如果不使用 using unwind,則無法通過聚合管道來執行此操作,但您可以使用update方法和$push運算子,作為一種解決方法,如下所示:
db.collection.update({
_id: "62821344445c30b35b441f11"
},
{
$push: {
watchHistory: {
"$each": [],
"$sort": {
seenTime: -1
},
}
}
})
請在此處查看作業示例
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/482215.html
上一篇:Pandas列串列中的單詞排序
下一篇:按照元素的特定順序對串列進行排序
