对于json文件,无法提取嵌套属性。
{
"Includes": {
"Employees": {
"14": {
"name": "john",
"age": 12,
"activity": {
"Count": 3502,
"RatingValue": 5
}
},
"17": {
"name": "smith",
"age": 23,
"activity": {
"Count": 232,
"RatingValue": 5
}
}
}
}
}
我期待输出为
14,约翰,12,3502,5
17,史密斯,23,232,5
我写的聚合函数不起作用
db.details.aggregate([
{ $unwind:"$Includes.Employees"},
{ $project : { name : "$Employees.name" , age:"$Employees.age", count:"$Employees.Count", RatingValue:"$Employees.RatingValue", _id:0} },
{ $out: "output" }
])
这里14和17可以是动态的。
答案 0 :(得分:0)
聚合管道无法处理此问题。使用JS:
步骤1:隐藏数据并保存到新的集合中,命名为"结果"
db.details.find().forEach(function(doc) {
var Employees = doc.Includes.Employees;
if (Employees) {
for ( var key in Employees) {
var Employee = Employees[key];
if (Employee) {
var item = {
id : key,
name : Employee.name,
age : Employee.age
};
var activity = Employee.activity;
if (activity) {
item.Count = activity.Count;
item.RatingValue = activity.RatingValue;
}
db.result.insert(item);
}
}
}
});
Setp 2:使用" mongoexport"
mongoexport -d mydb -c result --csv --fields id,name,age,Count,RatingValue --out output.csv