mongo操作

作者: wencst 分类: linux,数据库 发布时间: 2023-03-23 16:44 阅读: 1,851 次

1.查询

db.project.find();

2.加过滤条件

db.project.find({"_id":ObjectId("63ec87a135902f05cb3a62a8")});

3.加结果字段筛选

db.project.find({"_id":ObjectId("63ec87a135902f05cb3a62a8")},{_id:1,created:1,updated:1,title:1,comuser_id:1,status:1}

4.级联表处理

db.project.find({},{_id:1,created:1,updated:1,title:1,comuser_id:1,status:1}).forEach(
   function(item){
        var user_id = item.comuser_id;     
        var op = {_id: ObjectId(user_id)};     
        var user = db.user.findOne(op, {"_id":1,"username":1,"realname":1});        
        print(item._id,",",item.created,",",item.updated,",",item.title,",",item.status,",",user.username,",",user.realname,",");   
    } );

5.数据导出

导出方法一:

mongoexport --username=xxx --password=xxx --authenticationDatabase=admin --type=csv -f _id,created,updated,comuser_id,status -d clover -c project -o ./project.csv

导出方法二:

mongo -u xxx -p xxx --authenticationDatabase admin 127.0.0.1:27017/clover --eval 'db.project.find({},{_id:1,created:1,updated:1,title:1,comuser_id:1,status:1}).forEach(   function(item){     var user_id = item.comuser_id;     var op = {_id: ObjectId(user_id)};     var user = db.user.findOne(op, {"_id":1,"username":1,"realname":1});        print(item._id,",",item.created,",",item.updated,",",item.title,",",item.status,",",user.username,",",user.realname,",");   } );' > all.csv

导出方法三:

将方法二中的–eval中的代码写在eval.js脚本文件中

mongo -u xxx -p xxx --authenticationDatabase admin 127.0.0.1:27017/clover eval.js > all.csv

导出后,此时all.csv文件使用的是utf-8的格式,在excel中打开会展示中文乱码

iconv -s -c -f UTF8 -t GBK ./all.csv > all.gbk.csv

注意:

mongo shell查询时是分页查询的,在bash中执行mongo命令导出时,是全量执行的。

 

 

如果文章对您有用,扫一下支付宝的红包,不胜感激!

欢迎加入QQ群进行技术交流:656897351(各种技术、招聘、兼职、培训欢迎加入)



Leave a Reply