我有一個 Ranks 集合,其中包含如下所示的檔案:
[
{
"_id": "1",
"url": "ex1.com",
"keyword": "k1",
"rank": 19,
"createdAt": "2021-06-02",
"user": "616c542660d23fc17469b47e"
},
{
"_id": "2",
"url": "ex1.com",
"keyword": "k1",
"rank": 14,
"createdAt": "2021-06-01",
"user": "616c542660d23fc17469b47e"
},
{
"_id": "3",
"url": "ex1.com",
"keyword": "k2",
"rank": 8,
"createdAt": "2021-05-01",
"user": "616c542660d23fc17469b47e"
},
{
"_id": "4",
"url": "ex2.com",
"keyword": "k3",
"rank": 4,
"createdAt": "2021-05-01",
"user": "616c542660d23fc17469b47e"
}
]
包含如下檔案的用戶集合:
[
{
_id: "616c542660d23fc17469b47e",
email: "[email protected]"
}
]
我正在嘗試運行一個聚合,它將回傳按 url 分組的每個用戶物件 用戶的資料陣列,每個 url 物件都有包含唯一和最后(按日期)排名關鍵字的關鍵字陣列
這是我嘗試過的,但查詢回傳所有 url 的關鍵字,我怎樣才能讓它回傳唯一的和最后一個(按 createdAt 日期)關鍵字
Rank.aggregate([
{
$match: {}
},
{
$lookup: {
from: 'users',
localField: 'user',
foreignField: '_id',
as: 'user'
}
},
{
$project: {
user: {
$arrayElemAt: ['$user', 0]
},
url: '$url',
keyword: '$keyword',
rank: '$rank',
createdAt: '$createdAt',
}
},
{
$sort: {
createdAt: -1
}
},
{
$group: {
_id: '$user._id',
user: {
$first: '$user'
},
data: {
$push: {
id: '$_id',
url: '$url',
keyword: '$keyword',
rank: '$rank',
createdAt: '$createdAt',
}
}
}
}
])
預期輸出:
[{
user: {
_id: "616c542660d23fc17469b47e",
email: "[email protected]"
},
data: [
{
url: "ex1.com",
keywords: [
{
keyword: "k1",
rank: 19,
createdAt: "2021-06-02",
},
{
keyword: "k2",
rank: 8,
createdAt: "2021-05-01"
},
]
},
{
url: "ex2.com",
keywords: [
{
keyword: "k3",
rank: 4,
createdAt: "2021-05-01"
},
]
}
]
}]
uj5u.com熱心網友回復:
這是我提出的解決方案。操場
完整解釋:
我們按 "$url"、"$user" 和 "$keyword" 分組以獲得這些欄位的唯一組合。在這一點上,我們想要的只是唯一的關鍵字,但我們必須使用 user 和 url 欄位,因為我們稍后也會對這些欄位進行分組。因為我們按 createdAt 對它們進行排序,如果我們得到第一個檔案,它將是最后一個創建。
{
"$sort": {
"createdAt": 1
}
},
{
"$group": {
"_id": [
"$url",
"$user",
"$keyword"
],
"keywords": {
$first: "$$ROOT"
}
}
},
然后我們將這個關鍵字資訊格式化一下,以按 url 對其進行分組。此步驟將為我們提供每個 URL 的關鍵字。
{
"$project": {
"url": "$keywords.url",
"user": "$keywords.user",
"keywords": "$keywords",
"_id": 0
}
},
{
"$group": {
"_id": [
"$user",
"$url"
],
"data": {
$push: "$$ROOT"
}
}
},
最后,我們將按用戶對 URL 進行分組。請注意,我們在每個 groupBy 中按 URL 和用戶分組,以免丟失這些欄位。
{
"$project": {
"url": {
$first: "$data.keywords.url"
},
"user": {
$first: "$data.keywords.user"
},
"keywords": "$data.keywords",
"_id": 0
}
},
{
"$group": {
"_id": "$user",
"data": {
$push: "$$ROOT"
}
}
},
At this step we have almost all the information we needed grouped together. We would perform a lookUp to get the email from the Users collection and do the final mapping to remove some redundant data.
{
$lookup: {
from: "users",
localField: "_id",
foreignField: "_id",
as: "user"
}
},
{
"$unwind": "$user"
},
{
"$project": {
"_id": 0,
"data.user": 0,
"data.keywords._id": 0,
"data.keywords.url": 0,
"data.keywords.user": 0
}
},
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/326763.html
上一篇:無法在mongodb中啟用分片
