如何在mongo db

时间:2017-01-16 20:53:20

标签: json node.js mongodb export-to-csv

我的收藏夹有这样的文件

{
"_id" : ObjectId("587c8d0364b6e32706f7edef"),
"first_name" : "John",
"last_name" : "Doe",
"password" : "aasdjsabb12213b21bbcghc1h2",
"shift" : "A",
"dept" : "Management"
"Requests" : [
    {
        "weekId" : 1,
        "MO" : 1,
        "TU" : 2,
        "W" : 3,
        "TH" : 9,
        "FR" : 10,
        "SA" : 6,
        "SU" : 1
    }
  ]
}

我想将查询结果导出到csv,并且需要像这样展平的字段

{
"_id" : ObjectId("587c8d0364b6e32706f7edef"),
"first_name" : "John",
"last_name" : "Doe",
"password" : "aasdjsabb12213b21bbcghc1h2",
"shift" : "A",
"dept" : "Management"
"weekId" : 1,
"MO" : 1,
"TU" : 2,
"W" : 3,
"TH" : 9,
"FR" : 10,
"SA" : 6,
"SU" : 1

}

我正在尝试使用聚合功能,但无济于事。谁能建议我怎么做?

这是我的工作代码,但我不认为这是正确的方法

db.req.aggregate([{$unwind:'$Requests'},{$project:    {first_name:1,last_name:1,dept:1,"WeekId":"$Requests.weekdId","Mon":"$Requests.MO","Tue":"$Requests.TU","Wed":"$Requests.W","Thu":"$Requests.TH","Fri":"$Requests.FR","Sat":"$Requests.SA","Sun":"$Requests.SU"}},{$out:"results"}]);

1 个答案:

答案 0 :(得分:1)

您可以使用聚合查询执行此操作,但它不是很漂亮:

db.test.aggregate([
    {$unwind:"$Requests"},
    {$project:
         {_id:1,
          first_name:1,
          last_name:1,
          password:1,
          shift:1,
          dept:1,
          weekId:"$Requests.weekId",
          MO:"$Requests.MO",
          TU:"$Requests.TU",
          W:"$Requests.W",
          TH:"$Requests.TH",
          FR:"$Requests.FR",
          SA:"$Requests.SA",
          SU:"$Requests.SU"}}])
    .pretty()

所以基本上解开Requests数组,然后预测出你想要生成的文档。希望这是有道理的。