Redirect output of mongo query to a csv file

后端 未结 7 812
隐瞒了意图╮
隐瞒了意图╮ 2020-12-02 06:01

I am using MongoDB 2.2.2 for 32-bit Windows7 machine. I have a complex aggregation query in a .js file. I need to execute this file on the shell and direct the output to a C

7条回答
  •  北海茫月
    2020-12-02 06:46

    I use the following technique. It makes it easy to keep the column names in sync with the content:

    var cursor = db.getCollection('Employees.Details').find({})
    
    var header = []
    var rows = []
    
    var firstRow = true
    cursor.forEach((doc) => 
    {
        var cells = []
        
        if (firstRow) header.push("employee_number")
        cells.push(doc.EmpNum.valueOf())
    
        if (firstRow) header.push("name")
        cells.push(doc.FullName.valueOf())    
    
        if (firstRow) header.push("dob")
        cells.push(doc.DateOfBirth.valueOf())   
        
        row = cells.join(',')
        rows.push(row)    
    
        firstRow =  false
    })
    
    print(header.join(','))
    print(rows.join('\n'))
    

提交回复
热议问题