mongodb全新,我正在尝试以我需要的格式查询某些报告。
以下是我的资产收集的结果:
db.getCollection('Asset').find({})
结果:
/* 1 */
{
"_id" : ObjectId("58176238f23ee4040a48846c"),
"AssetTypeId" : "58176225f23ee4040a48846b",
"AssetTypeName" : "Chairs",
"Fields" : [
{
"_id" : "5770ae6cf500fd7675c234c5",
"Title" : "Asset Name",
"Value" : "Fancy Chair"
},
{
"_id" : "576b7593f500fd7675c234b9",
"Title" : "Status",
"Value" : "Missing"
},
{
"_id" : "57b2b52b31f7c7d80db34a23",
"Title" : "Location",
"Value" : "Office")
}
]
}
/* 2 */
{
"_id" : ObjectId("5817638ff23ee4040a48846e"),
"AssetTypeId" : "58176225f23ee4040a48846b",
"AssetTypeName" : "Chairs",
"Fields" : [
{
"_id" : "5770ae6cf500fd7675c234c5",
"Title" : "Asset Name",
"Value" : "Basic Chair"
},
{
"_id" : "576b7593f500fd7675c234b9",
"Title" : "Status",
"Value" : "Stores"
},
{
"_id" : "57b2b52b31f7c7d80db34a23",
"Title" : "Location",
"Value" : "Home")
}
]
}
/* 3 */
{
"_id" : ObjectId("581767f3f23ee4040a488471"),
"AssetTypeId" : "5817678ff23ee4040a488470",
"AssetTypeName" : "Table",
"Fields" : [
{
"_id" : "5770ae6cf500fd7675c234c5",
"Title" : "Asset Name",
"Value" : "Fancy Table"
},
{
"_id" : "576b7593f500fd7675c234b9",
"Title" : "Status",
"Value" : "Active"
},
{
"_id" : "57b2b52b31f7c7d80db34a23",
"Title" : "Location",
"Value" : "Office")
}
]
}
这是我试图从查询中获得的最终结果:
[
{"Asset Name":"Fancy Chair", "Status":"Missing","Location":"Office","AssetTypeName":"Chairs"},
{"Asset Name":"Basic Chair", "Status":"Stores","Location":"Office","AssetTypeName":"Chairs"},
{"Asset Name":"Fancy Table", "Status":"Active","Location":"Office","AssetTypeName":"Table"}
]
答案 0 :(得分:0)
您只需要通过迭代结果并创建新的对象数组,将mongodb 资产结果转换为首选格式:
function processAssets(assets){
var results = [];
for (var i=0;i<assets.length;i++){
var asset = assets[i];
var result = {AssetTypeName: asset.AssetTypeName};
//AssetTypeName is not in the Fields array
for (var f=0;f<asset.Fields.length;f++){
var field = asset.Fields[f];
result[field.Title] = field.Value;
//this will make result['Asset Name'] = 'Fancy Chair', etc
}
results.push(result);
}
return results;
}
更多的mongodb方法是使用cursor.map方法:
db.Asset.find().map(function(asset){
var result = {AssetTypeName: asset.AssetTypeName};
for (var f=0;f<asset.Fields.length;f++){
var field = asset.Fields[f];
result[field.Title] = field.Value;
}
return result;
});