2017-12-02 70 views
0

我希望能夠計算每個州的經銷商數量。我遇到的麻煩是我的城市/州/郵編全部在一列中。所以,我需要一種方法來從中抽象出唯一的狀態。Mongo從多字段列抽象字段

這是我的一個結果的例子。

"_id" : ObjectId("5a22c8e562c2e489c5df710a"), 
     "2016rank" : 22, 
     "Dealershipgroupname" : "West-Herr Automotive Group Inc.", 
     "Address" : "3552 Southwestern Blvd.", 
     "City/State/Zip" : "Orchard Park, NY 14127", 
     "Phone" : "(716) 926-7052", 
     "Companywebsite" : "www.westherr.com", 
     "Topexecutive" : "Scott Bieler", 
     "Topexecutivetitle" : "president", 
     "Totalnewretailunits" : "29,486", 
     "Totalusedunits" : "20,525", 
     "Totalfleetunits" : 302, 
     "Totalwholesaleunits" : "23,694", 
     "Total_units" : "74,007", 
     "Total_number_of _dealerships" : 25, 
     "Grouprevenuealldepartments*" : "$1,805,200,100", 
     "2015rank" : 20 

這是我寫的聚合組代碼,但我希望它只使用狀態。

db.car.aggregate([ 
    {"$group" : {_id:"$City/State/Zip", count:{$sum:1}}} 
]) 

那麼,我將如何從City/State/Zip抽象出狀態,並在我的聚合中使用它?

回答

0

你可以試試這個。

db.car.aggregate([ 
    { $project : { city_state : { $split: ["$City/State/Zip", " "] } } }, 
    { $unwind : "$city_state" }, 
    { $match : { city_state : /[A-Z]{2}/ } }, 
    { $group : {_id:{ "state" : "$city_state" }, count:{$sum:1}}} 
])