考虑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" } }
您可以使用游标方法 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"
}
}