2012-11-15 95 views
2

Mongo noob here。如何在mongodb中使用聚合?

好吧,我有一個總共約30000個拉鍊。

它們看起來像這樣...

{ "city" : "EPES", "loc" : [ -88.161443, 32.763371 ], "pop" : 1391, "state" : "AL", "_id" : "35460" } 
{ "city" : "ETHELSVILLE", "loc" : [ -88.221987, 33.386816 ], "pop" : 719, "state" : "AL", "_id" : "35461" } 
{ "city" : "EUTAW", "loc" : [ -87.930297, 32.888871 ], "pop" : 6586, "state" : "AL", "_id" : "35462" } 
{ "city" : "FOSTERS", "loc" : [ -87.735688, 33.135859 ], "pop" : 2100, "state" : "AL", "_id" : "35463" } 
{ "city" : "GAINESVILLE", "loc" : [ -88.271558, 32.908364 ], "pop" : 1051, "state" : "AL", "_id" : "35464" } 
{ "city" : "GORDO", "loc" : [ -87.900504, 33.346917 ], "pop" : 4333, "state" : "AL", "_id" : "35466" } 
{ "city" : "KNOXVILLE", "loc" : [ -87.791855, 32.982423 ], "pop" : 373, "state" : "AL", "_id" : "35469" } 
{ "city" : "COATOPA", "loc" : [ -88.173592, 32.588509 ], "pop" : 6055, "state" : "AL", "_id" : "35470" } 
{ "city" : "CYPRESS", "loc" : [ -87.615134, 32.978853 ], "pop" : 2659, "state" : "AL", "_id" : "35474" } 
{ "city" : "NORTHPORT", "loc" : [ -87.591441, 33.283425 ], "pop" : 20114, "state" : "AL", "_id" : "35476" } 

我需要4最郵政編碼找到利用它聚集的狀態......我不知道。

任何幫助理解

+0

我假設這是作業嗎?從一個「聚合」電話開始,每個州都會產生一些郵政編碼,然後從那裏開始。 – JohnnyHK

+0

正如我所說...不知道。我正在看mongo網站上的例子,以獲得線索...... http://docs.mongodb.org/manual/tutorial/aggregation-examples/ – thefonso

回答

4

溶液:

db.zips.aggregate([ {$group:{_id:{state:"$state"},numberOfzipcodes:{$sum:1}}}, {$sort:{numberOfzipcodes:-1}}, {$limit:4}]) 
2

//組通過狀態,然後找到總的郵政編碼中的每個狀態,排序總數 的郵政編碼//降序訂購。然後使用跳過跳過前3個狀態並限制爲1

db.zips.aggregate([{$ group:{_ id:{state:「$ state」},zips:{$ sum:1}}} ,{$ sort:{zips:-1}},{$ skip:3},{$ limit:1}])