从现有表格中将文档插入mongodb

时间:2017-12-07 14:28:35

标签: mongodb

我正在尝试在mongo中编写一个查询,它将创建一个新表,遍历我的数据集,并将TopExecutiveTitle插入到新表中。我也希望它能保持每个位置的计数,并且只有在新的时候才会在表格中插入一个位置。

这是我到目前为止所拥有的。此代码循环遍历我的表并将TopExectuiveTitle插入到新表中。但是,它不会将它们组合在一起并保持计数。如何编写查询以便它可以?

db.car.find().forEach( function (x) {
db.TopExecutiveTable.insert({Topexecutivetitle: x.Topexecutivetitle}) 
});

以下是我数据库中文档的示例。

{
    "_id" : ObjectId("5a22c8e562c2e489c5df70fa"),
    "2016rank" : 1,
    "Dealershipgroupname" : "AutoNation Inc.?",
    "Address" : "200 S.W. 1st Ave.",
    "City/State/Zip" : "Fort Lauderdale, FL 33301",
    "Phone" : "(954) 769-7000",
    "Companywebsite" : "www.autonation.com",
    "Topexecutive" : "Mike Jackson",
    "Topexecutivetitle" : "chairman & CEO",
    "Totalnewretailunits" : "337,622",
    "Totalusedunits" : "225,713",
    "Totalfleetunits" : 3,
    "Totalwholesaleunits" : "82,342",
    "Total_units" : "649,415",
    "Total_number_of _dealerships" : 260,
    "Grouprevenuealldepartments*" : "$21,609,000,000",
    "2015rank" : 1
}

我想要的结果是这样的

"Topexecutivetitle" : "chairman & CEO" 
           "Count"  : 3
"Topexecutivetitle" : "president" 
           "Count"  : 7
}

1 个答案:

答案 0 :(得分:0)

要做到这一点,你需要使用mongo的aggregate功能,如下所示:

db.car.aggregate([
{
    $group:{
            _id:"$Topexecutivetitle",
            count:{$sum:1}
        }
},
{
    $project:{
            Topexecutivetitle:"$_id",
            count:1,
            _id:0
        }
 },
 {
     $out:"result"
 }])

这将为您提供所需的输出并将其存储到新的集合"结果":

{
    "_id" : "president",
    "count" : 1.0
},
{
    "_id" : "chairman & CEO",
    "count" : 3.0
}