search

Home  >  Q&A  >  body text

mongodb - mongo怎么导出一个内嵌数组中的某些信息

比如这样

{
  "_id": 1,
  "array": [
    {"name": "a", "price": "2","amount":1},
    {"name": "b", "price": "2","amount":2},
    {"name": "c", "price": "3","amount":4}  
  ] 
}

我只想把name属性和price属性导出,该怎么做呢?用mongoexport貌似无法实现啊,诸位有什么好的办法吗?求教了

伊谢尔伦伊谢尔伦2757 days ago589

reply all(1)I'll reply

  • 怪我咯

    怪我咯2017-05-02 09:21:33

    mongo supports js scripts, and you can use javascript scripts to batch process and export data:

    #!/usr/bin/env mongo
    db = db.getSiblingDB(db_name)
    // db.auth("user", "passwd");
    
    result = {};
    db.clt_name.find().forEach(function(r) {
        // 这里是回调函数,r就是每一条记录,是一个object对象,可以遍历r.array,把需要的属性存入result
    })
    
    for (var key in result) {
        // 按照你希望的格式输出:
        print(key + "\t" + result[key])
    }

    For functions that can be used in the mongo environment, see Write Scripts for the mongo Shell

    reply
    0
  • Cancelreply