自己常用的mongodb操作指南
一、将数据读入MongoDB
1.mysql数据读入MongoDB
(1)获取mysql数据库中所有字段名,按照逗号分隔
SELECT GROUP_CONCAT(COLUMN_NAME SEPARATOR ",")
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = '数据库名' AND TABLE_NAME = '表名'
(2)将数据导出问csv格式,字段间用逗号分隔
select * from bankrecord limit 10
into outfile '/bankrecord1.csv'
fields terminated by ',' optionally enclosed by "" escaped by "" lines terminated by '\r\n';
(3)将数据导入到MongoDB中
mongoimport -h localhost -d dbw -c bankrecord -f '前面获取到的字段名逗号分隔的值' --type csv -file D:\bankrecord1.csv
(4)如果存在双引号的话怎么导入?
2.使用kettle将mysql数据导入MongoDB中
1)打开kettle,选择“转换”
2)点击“核心对象”并选择“输入”中的“表输入”,拖拽到空白区域,并双击编辑信息,如果没有引入mysql数据库连接的jar包的话,先下载mysql连接jar包,然后再jar包拷贝到kettle的lib文件夹下,重启工具即可
3)选择“output”中的“JSON OUTPUT”,拖拽到编辑区域,按住shift连接第二步和这一步,并双击编辑信息
“一般”的“操作”选择“output value”
“字段”选项中点击“获取字段”,最后点击“确定”即可。
4)选择“Big Data”中的“MongoDB Output”,拖拽到编辑区域,按住shift连接第二步和这一步,并编辑信息。
在第一栏中填写数据库连接信息,在第二栏选择库名和collection名,第三栏获取字段
5.保存转换,然后点击运行按钮,点击之后好像不用配置别的项目了
3.使用python实现将csv文件读入mongodb中
import csv
import pymongo
client = pymongo.MongoClient('localhost',27017)
db = client['ceshi']
collection = db['ceshi']
cread = csv.reader(open('C:/Users/17646/Desktop/bank2.csv'))
index = 0
for row in cread:
if index != 0:
rec = {'id':row[1], 'fromName':row[2], 'fromId':row[3], 'toName':row[4], 'toId':row[5], 'date':row[6],
'money':row[7], 'date2':row[8], 'time':row[9], 'date2ToDay':row[10],
'minuteTtimestamp':row[11], 'state':row[12], 'ttimestamp':row[13], 'fromId2':row[14], 'toId2':row[15]}
collection.insert_one(rec)
# print(row[0])
index = index + 1
二、mongodb查询语句
1.group
(1)在pymongo中的写法:
reduce='''
function ( curr, result ) {
result.total += 1;
result.sum+=curr['rmbje'];
}
'''
finalize = '''
function(result){
result.avg = result.sum/result.total;
}
'''
collection.group({ 'jyrq': 1},{ 'fkfmc': 'XXX'},{'total':0,'sum':0},reduce,finalize)
下面是函数原型:
group(key, condition, initial, reduce, finalize=None)
key是需要分组的键,可以是list
condition是条件,和find的一样
initial是初始的一个对象,比如你要统计每个分组的元素个数,你可以传递一个{‘sum’:0}
reduce是一个string,内容是js的函数,形式是:
function(obj, prev)
group先按照key进行分组,然后每个分组,对分组内的元素依次调用reduce函数,
obj是当前元素,prev是上一个元素处理过的初始化的那个对象。
第一个元素接受到的obj就是initial的,然后第二个元素接收到的第一个元素处理过之后的。
(2)在mongodb中命令行查询写法:
参考地址:https://docs.mongodb.com/manual/reference/command/group/
db.getCollection('bank_record').group({
key: { 'skfmc': 1 },
cond: { 'fkfmc': 'XXX'},
$reduce: function ( curr, result ) {
result.total += 1;
result.sum+=curr['rmbje'];
},
initial: {total:NumberInt(0),sum:0},
finalize: function(result){
result.avg = result.sum/result.total;
}
})
2.distinct
(1)使用distinct语句
https://docs.mongodb.com/manual/reference/method/db.collection.distinct/
db.collection.distinct(field, query, options)
Results must not be larger than the maximum BSON size. If your results exceed the maximum BSON size, use the aggregation pipeline to retrieve distinct values using the $group operator, as described in Retrieve Distinct Values with the Aggregation Pipeline.
不过好像这个方法只能对一个字段进行distinct,两个字段就不行了。
(2)使用aggregation管道检索不同的值
使用$group操作符对数据进行聚合。
数据格式:
{ "_id" : 1, "item" : "abc", "price" : 10, "quantity" : 2, "date" : ISODate("2014-03-01T08:00:00Z") }
{ "_id" : 2, "item" : "jkl", "price" : 20, "quantity" : 1, "date" : ISODate("2014-03-01T09:00:00Z") }
{ "_id" : 3, "item" : "xyz", "price" : 5, "quantity" : 10, "date" : ISODate("2014-03-15T09:00:00Z") }
{ "_id" : 4, "item" : "xyz", "price" : 5, "quantity" : 20, "date" : ISODate("2014-04-04T11:21:39.736Z") }
{ "_id" : 5, "item" : "abc", "price" : 10, "quantity" : 10, "date" : ISODate("2014-04-04T21:23:13.331Z") }
查询语句:
db.sales.aggregate( [ { $group : { _id : "$item" } } ] )
3.find语句中添加过滤条件和筛选指定列
db.getCollection('bankrecord').find(
{"XXX":{"$ne": null,"$ne":"","$exists":true},"XXXX":{"$ne":null,"$ne":"","$exists":true}},{"_id":0,"fkfzjhm":1,"skfzjhm":1})
“XXX”:{"$ne": null,"$ne":"","$exists":true}表示的是要求字段存在且不为null和空字符串;
{"_id":0,“f1”:1,“f2”:1}表示的是只需要取出f1和f2字段,MongoDB的默认_id不取出。
三、mongodb数据导出
1.导出csv
mongoexport -d ceshi -c result -f id,pagerank,inCount,outCont --csv -o result.csv