第一天学习 - 辛酸历程
1. 在linux上搭建 mongodb 单机环境 - 结果 服务器搭建成功 本地连接不上
2. 在windows 上搭建 mongodb 单机环境 - 结果 服务器搭建成功 本地成功连接
3. 接公司的一个java mongodb数据分拣项目 脑子都炸了,mongo 不懂 linux菜鸡 来搞。
下面来先了解下 mongodb的增删改查吧
1.通过java 连接 mongo数据库
MongoClient client = new MongoClient( "localhost", 27017); //数据库地址
MongoDatabase database = client.getDatabase( "local" ); //数据库名
MongoCollection<Document> collection = database.getCollection("test" ); //获取集合
[这样就连接得到数据库了 ]
/**
*1. 插入一条数据 测试成功
* */
collection.insertOne(new Document("name","张三").append("age", 20));
/**
* 2.连接 news_sina_weibo
* 获取数据、 往user表里添加
* */
//1.获取微博集合
MongoCollection<Document> weibo = database.getCollection("news_sina_weibo" );
//2.获取user集合需要的值
FindIterable<Document>it =weibo.find();//查询全部
MongoCursor<Document> cursor=it.iterator();//获取游标
while(cursor.hasNext()) { //循环遍历,获取userid nickname avatar
Document doc = cursor.next(); //取出每一行数据
String userid= doc.getString("userid");//用户id
String nickname= doc.getString("nickname");//用户昵称
String avatar= doc.getString("avatar");//用户头像
String param = getUUID();
/**
* 1.插入user
* */
MongoCollection<Document> user = database.getCollection("user" );
Date now = new Date();
String json = " {" +
" 'socialId' : '"+getUUID()+"', " +
" 'type' : '"+getType()+"', " +
" 'seqence':'"+ getUUID() +"' " +
" } ";
String json1 = " {" +
" 'nickname' :'"+nickname +"', " +
" 'avatar' : '"+avatar+"' ," +
" 'adress' :'"+getCity()+"' " +
" } ";
String json2=" {" +
" 'password' : '"+getUUID()+"', " +
" 'mobile' : null, " +
" 'updateTime' :'"+now+"' " +
" } ";
DBObject bson = (DBObject)JSON.parse(json);
DBObject bson1 = (DBObject)JSON.parse(json1);
DBObject bson2 = (DBObject)JSON.parse(json2);
//插入user集合 [行]
Document document1= new Document/*("_id","").append*/
("createTime", now).append("updatedTime", now).append("profile",bson1).append("experience", getNumber())
.append("subChannel", null).append("device", "").append("social", bson).append("account", bson2)
.append("userid", userid);
user.insertOne(document1); // 批量插入 user
也不知道这样写对不对,就是写的测试,希望大神看到指正,以免以后出问题了,
差不多 插入后结构就是这个样子了,剩下的该怎么做呢,啊 绝望