我在 MongoDB 中有一個集合(4.4,但版本對我來說并不重要),其中一個檔案值是一個 URL 陣列。每個檔案(在陣列內)會有多個具有多個 URL 的檔案,其中一些 URL 已經存在。我想選擇每個 URL 最早出現的每個檔案(目的是將其標記為“來源”。
樣本收集的 MongoPlayground 鏈接 - https://mongoplayground.net/p/ZAgCqr517-8
{
"title": "story1_first",
"isoDate": "2022-01-01T00:00:00.000Z",
"links": [
"www.first.com/article1",
"www.anotherdomain.com"
]
},
{
"title": "story1_mention",
"isoDate": "2022-01-10T00:00:00.000Z",
"links": [
"www.first.com/article1",
"www.somesite.com"
]
},
{
"title": "story2_first",
"isoDate": "2022-01-20T00:00:00.000Z",
"links": [
"www.newstory.com/article2",
"www.anothercompany.com"
]
},
{
"title": "story2_mention",
"isoDate": "2022-01-20T00:00:00.000Z",
"links": [
"www.newstory.com/article2",
"www.anothercompany.com"
]
}
]
在此示例中,我希望查詢/聚合回傳標題中帶有“第一個”的兩個檔案,因為它們是在“鏈接”中共享公共 URL 的檔案,并且是具有最早日期的檔案。類似于搜索引擎如何根據鏈接到它的其他站點的數量來對站點進行排名。
uj5u.com熱心網友回復:
您可以在聚合管道中執行以下操作:
$unwindlinks所以檔案處于鏈接級別$sort開始isoDate獲取第一個檔案$group通過links獲取組和第一個檔案的ID之間的計數。在您的示例中,標題被視為唯一識別符號。$match計數 > 1 以獲得title共享相同鏈接$group對我們在步驟 3 中找到的唯一識別符號進行重復資料洗掉$lookup把原來的檔案拿回來,做一些化妝品$replaceRoot
db.collection.aggregate([
{
"$unwind": "$links"
},
{
$sort: {
isoDate: 1
}
},
{
$group: {
_id: "$links",
first: {
$first: "$title"
},
count: {
$sum: 1
}
}
},
{
$match: {
count: {
$gt: 1
}
}
},
{
$group: {
_id: "$first"
}
},
{
"$lookup": {
"from": "collection",
"localField": "_id",
"foreignField": "title",
"as": "rawDocument"
}
},
{
"$unwind": "$rawDocument"
},
{
"$replaceRoot": {
"newRoot": "$rawDocument"
}
}
])
這是Mongo游樂場供您參考。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/410189.html
標籤:
上一篇:如何構建這些需求?(微服務)
下一篇:在子物件陣列中包含父欄位
