Mongodb Aggregate计算平均值并将其添加到文档中

时间:2017-01-09 13:44:28

标签: mongodb mongodb-query aggregation-framework

我有websites,其中包含2个文档:

{
    "_id" : ObjectId("58503934034b512b419a6eab"),
    "website" : "https://www.stackoverflow.com",
    "name" : "Stack Exchange",
    "keywords" : [ 
        "helping", 
        "C#", 
        "PYTHON"
    ]
}

{
    "_id" : ObjectId("58503934034b512b419a6eab"),
    "website" : "https://www.google.com.com",
    "name" : "Stack Exchange",
    "keywords" : [ 
        "search", 
        "engine", 
    ]
}

我还有另一个seo_tracking,其中包含:

{
    "_id" : ObjectId("587373d6f6325811c8a0b3ad"),
    "position" : "2",
    "real_url" : "https://www.stackoverflow.com",
    "created_at" : ISODate("2017-01-09T11:28:22.104Z"),
    "keyword" : "helping"
},
{
   "_id" : ObjectId("587373d6f6325811c8a0b3ad"),
   "position" : "4",
   "real_url" : "https://www.stackoverflow.com",
   "created_at" : ISODate("2017-01-09T11:28:22.104Z"),
   "keyword" : "C#"
}

等。这包含大约100多个文件

我想要做的是汇总seo_tracking与特定网址website www.stackexchangewebsites}中的www.stackoverflow.com匹配seo_tracking websites))我可以做得很好。但是,我想返回以下{ "_id" : ObjectId("587373d6f6325811c8a0b3ad"), "website":"https://www.stackoverflow.com", "avg_position" : "2" } 中的每一个:

avg_position

然后是Google等。即使db.seo_tracking.aggregate([ { $lookup: { from: "websites", localField: "real_url", foreignField: "website", as: "post_websites" }, }, { "$group": { _id:null, avg_position:{$avg:"$position"} } } ]) 为0,我也尝试了以下内容:

{
    "_id" : null,
    "avg_position" : 2.0
}

然而,这只会产生:

website

我需要做的是ID,理想情况下还需要CREATE TABLE dbo.TEST_ASC(ID INT IDENTITY(1,1) ,RandNo FLOAT ); GO CREATE CLUSTERED INDEX cidx ON dbo.TEST_ASC(ID ASC); GO CREATE TABLE dbo.TEST_DESC(ID INT IDENTITY(1,1) ,RandNo FLOAT ); GO CREATE CLUSTERED INDEX cidx ON dbo.TEST_DESC(ID DESC); GO INSERT INTO dbo.TEST_ASC VALUES(RAND()); GO 100000 INSERT INTO dbo.TEST_DESC VALUES(RAND()); GO 100000

对于我在哪里出错的任何想法?

1 个答案:

答案 0 :(得分:2)

你可以尝试这样的事情。您需要$unwind才能访问已加入集合中的字段,并更改您的分组密钥以使用已加入集合中的_id来获取每个网站的平均值:

db.seo_tracking.aggregate([{
    $lookup: {
        from: "website",
        localField: "real_url",
        foreignField: "website",
        as: "post_websites"
    },
}, {
    $unwind: "$post_websites"
}, {
    "$group": {
        _id: "$post_websites._id",
        avg_position: {
            $avg: "$position"
        },
        website: {
            $first: "$real_url"
        }
    }
}])