我有一組網站,每個網站都包含正在跟蹤的網站及其關鍵字列表。我還有另一個名爲「排名」的集合,它對網站中的每個關鍵字都包含排名。收集到目前爲止是這樣的:MongoDB - 查找單個匹配文檔的嵌入式陣列中的第一個和最後一個
{
"_id" : ObjectId("58503934034b512b419a6eab"),
"website" : "https://www.google.com",
"name" : "Google",
"keywords" : [
"Search",
"Websites",
],
"tracking" : [
{
"_id" : ObjectId("5874aa1df63258286528598d"),
"position" : 0,
"created_at" : ISODate("2017-01-1T09:32:13.831Z"),
"real_url" : "https://www.google.com",
"keyword" : "Search"
},
{
"_id" : ObjectId("5874aa1ff63258286528598e"),
"keyword" : "Search",
"real_url" : "https://www.google.com",
"created_at" : ISODate("2017-01-2T09:32:15.832Z"),
"found_url" : "https://google.com/",
"position" : 3
},
{
"_id" : ObjectId("5874aa21f63258286528598f"),
"keyword" : "Search",
"real_url" : "https://www.foamymedia.com",
"created_at" : ISODate("2017-01-3T09:32:17.017Z"),
"found_url" : "https://google.com/",
"position" : 2
},
{
"_id" : ObjectId("5874aa21f63258286528532f"),
"keyword" : "Websites",
"real_url" : "https://www.google.com",
"created_at" : ISODate("2017-01-1T09:32:17.017Z"),
"found_url" : "https://google.com/",
"position" : 1
},
{
"_id" : ObjectId("5874aa21f63258286528542f"),
"keyword" : "Websites",
"real_url" : "https://www.google.com",
"created_at" : ISODate("2017-01-1T09:32:17.017Z"),
"found_url" : "https://google.com/",
"position" : 2
},
]
}
我想要做的是:
1)組中的所有關鍵字一起通過關鍵字
2)找到起始位置(在本月的最開始)
3)查找當前位置(今天的)
所以理論上我希望接受的對象,如:
{
"_id" : ObjectId("58503934034b512b419a6eab"),
"website" : "https://www.google.com",
"tracking" : [
{
"_id" : ObjectId("5874aa1df63258286528598d"),
"keyword": "Search",
"start_position": 0,
"todays_position": 3,
},
{
"_id" : ObjectId("5874aa1df63258286528598d"),
"keyword": "Website",
"start_position": 0,
"todays_position": 2,
},
]
雖然我對如何在另一個字段上進行分組感到困惑。我已經試過到目前爲止以下:
db.getCollection('websites').aggregate([
{
$lookup: {
from: "seo_tracking",
localField: "website",
foreignField: "real_url",
as: "tracking"
}
},
{
$match: {
"_id" : ObjectId("58503934034b512b419a6eab")
}
},
{
$group: {
"_id" : "$_id",
"keyword" : {
$first: "$tracking.keyword",
},
}
}
]);
但這不是由關鍵字分組,我也不能找出我將如何得到的預期值。
你有什麼第二個集合? –
@Sergey Berezovskiy感謝您的回覆。另一個集合包含第一個輸出中'tracking'內的所有內容。我已經使用聚合,以結合兩個 – Phorce
@SergeyBerezovskiy我已經知道關鍵字和排名..問題是,他們重複,因爲數據收集整個月..我只需要捕獲,關鍵字的foreach,顯示在月初的位置和今天的位置 - 任何想法? – Phorce