2015-07-20 78 views
2

考慮MongoDB的zip codes aggregation示例data set。集合中的每個文檔如下所示:如何將MongoDB集合轉換爲元素值上的對象?

{ 
    "_id": "10280", 
    "city": "NEW YORK", 
    "state": "NY", 
    "pop": 5574, 
    "loc": [ 
    -74.016323, 
    40.710537 
    ] 
} 

如何轉變集合到一個對象,其中每個鍵是一個字段的值,並且每個值在集合中的對象?

例如,給出兩個文件

{ "_id" : "01001", "city" : "AGAWAM", "loc" : [ -72.622739, 42.070206 ], "pop" : 15338, "state" : "MA" } 
{ "_id" : "01002", "city" : "CUSHMAN", "loc" : [ -72.51564999999999, 42.377017 ], "pop" : 36963, "state" : "MA" } 

如何轉變成一個單一的文件

{ 
    "01001": { "_id" : "01001", "city" : "AGAWAM", "loc" : [ -72.622739, 42.070206 ], "pop" : 15338, "state" : "MA" }, 
    "01002": { "_id" : "01002", "city" : "CUSHMAN", "loc" : [ -72.51564999999999, 42.377017 ], "pop" : 36963, "state" : "MA" } 
} 

我在嘗試MongoDB shell命令db.zips.aggregate({$project: { "$_id":"$$CURRENT"}}).pretty(),我收到錯誤消息$expressions are not allowed at the top-level of $project

我使用的MapReduce與命令db.zips.mapReduce(function(){emit(this._id, this)},function(k,v){}, {out:"stuffs"})也試過但是,這並不奇怪,只是生產(含db.stuffs.find()

{ "_id" : "01001", "value" : { "_id" : "01001", "city" : "AGAWAM", "loc" : [ -72.622739, 42.070206 ], "pop" : 15338, "state" : "MA" } } 
{ "_id" : "01002", "value" : { "_id" : "01002", "city" : "CUSHMAN", "loc" : [ -72.51565, 42.377017 ], "pop" : 36963, "state" : "MA" } } 

回答

1

您可以使用光標方法forEach()迭代的find()光標和訪問然後可以將這些文檔添加到對象變量中,如以下示例中的兩個文檔所示:

var obj = {}; 
var iterator = function(doc){ 
    obj[doc._id] = doc; 
} 
db.collection.find({}).forEach(iterator); 
printjson(obj); 

輸出

{ 
    "01001" : { 
     "_id" : "01001", 
     "city" : "AGAWAM", 
     "loc" : [ 
      -72.622739, 
      42.070206 
     ], 
     "pop" : 15338, 
     "state" : "MA" 
    }, 
    "01002" : { 
     "_id" : "01002", 
     "city" : "CUSHMAN", 
     "loc" : [ 
      -72.51565, 
      42.377017 
     ], 
     "pop" : 36963, 
     "state" : "MA" 
    } 
} 
+1

謝謝,@chridam。我正在尋找一種只有查詢的方式來做到這一點,沒有遊標。我的問題應該更具體一些。 –

+0

@MatthewAdams,請使用[$ unwind](https://docs.mongodb.com/manual/reference/operator/aggregation/unwind/) –

相關問題