如何将 MongoDb 查询转换为 csv(excel 格式)

How to convert MongoDb query into csv (excel format)

这是我的查询。我想将此查询的输出导出为 csv(excel 格式),这样我就可以获得 table 数据。我怎样才能做到这一点?我正在使用 Robo3t。

(db.getCollection('sentimentOpinions').aggregate([ 
  { $match : { objectType : "Security" } },

  { $lookup:{
             from: "securities",       
       localField: "objectId",  
     foreignField: "id",
               as: "StockID" }},

  { $unwind:"$StockID" },

  { $lookup:{
             from: "users", 
       localField: "userId", 
     foreignField: "userId",
               as: "USER_ARJ" }},

  { $unwind:"$USER_ARJ" },

  {$project :{USER_ID : "$userId",
                NAME : { $concat: [ "$USER_ARJ.profile.firstName",", ", 
                                 "$USER_ARJ.profile.lastName" ] }, 
          SECURITY_ID: "$StockID.id", 
             SECURITY: "$StockID.displayName", 
               TICKER: "$StockID.symbols.yahoo",
        OPINION_VALUE: "$value",
         OPINION_DATE: "$opinionDate"}}, 

         { $sort : { OPINION_DATE : -1 } } ]))

首先,您需要使用此查询对数据进行正确格式化,并使用 $out

将输出另存为 collection 作为 new_col
        (db.getCollection('sentimentOpinions').aggregate([ 
      { $match : { objectType : "Security" } },

      { $lookup:{
                 from: "securities",       
           localField: "objectId",  
         foreignField: "id",
                   as: "StockID" }},

      { $unwind:"$StockID" },

      { $lookup:{
                 from: "users", 
           localField: "userId", 
         foreignField: "userId",
                   as: "USER_ARJ" }},

      { $unwind:"$USER_ARJ" },

      {$project :{USER_ID : "$userId",
                    NAME : { $concat: [ "$USER_ARJ.profile.firstName",", ", 
                                     "$USER_ARJ.profile.lastName" ] }, 
              SECURITY_ID: "$StockID.id", 
                 SECURITY: "$StockID.displayName", 
                   TICKER: "$StockID.symbols.yahoo",
            OPINION_VALUE: "$value",
             OPINION_DATE: "$opinionDate"}}, 

             { $sort : { OPINION_DATE : -1 } },
           {"$out" : "new_col"}
 ]))

现在您可以使用 mongoexport

导出您想要的新 collection 格式
mongoexport --db db_name --collection new_col_name(new_col) --type csv --fields USER_ID,NAME,SECURITY_ID,SECURITY,TICKER,OPINION_VALUE,OPINION_DATE --out out_file.csv