$ cd ~/Downloads # 进入下载目录 $ wget -c http://res.aihyzh.com/大数据技术原理与应用3/05/mongodb-linux-x86_64-ubuntu1604-4.4.4.tgz #下载资源 $ sudo tar -zxvf ~/Downloads/mongodb-linux-x86_64-ubuntu1604-4.4.4.tgz -C /usr/local $ cd /usr/local $ sudo mv mongodb-linux-x86_64-ubuntu1604-4.4.4/ mongodb $ sudo chown -R stu:stu mongodb # 赋予权限
dbpath=/usr/local/mongodb/data logpath=/usr/local/mongodb/log/mongodb.log logappend=true port=27017 fork=true dbpath #数据存储目录 logpath #日志文件路径 logappend #追加 port #端口号 fork #后台进程
启动MongoDB
/usr/local/mongodb/bin/mongod -f /usr/local/mongodb/mongodb.conf 启动之后该窗口不能关闭,否则MongoDB服务会断开。
3.2.2 使用Shell命令操作MongoDB
- 进入MongoDB Shell模式
输入如下命令进入MongoDB Shell模式:
$ /usr/local/mongo \
import java.util.ArrayList;
import java.util.List;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
public class TestMongoDB {
public static void main(String[] args) {
find();
}
public static MongoCollection<Document> getCollection(String dbname,String collectionname){
MongoClient mongoClient=new MongoClient("localhost",27017);
MongoDatabase mongoDatabase = mongoClient.getDatabase(dbname);
MongoCollection<Document> collection = mongoDatabase.getCollection(collectionname);
return collection;
}
public static void insert(){
try{
MongoCollection<Document> collection= getCollection("School","student");
Document doc1=new Document("sname","Mary").append("sage", 25);
Document doc2=new Document("sname","Bob").append("sage", 20);
List<Document> documents = new ArrayList<Document>();
documents.add(doc1);
documents.add(doc2);
collection.insertMany(documents);
System.out.println("插入成功");
}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}
public static void find(){
try{
MongoCollection<Document> collection = getCollection("School","student");
MongoCursor<Document> cursor= collection.find().iterator();
while(cursor.hasNext()){
System.out.println(cursor.next().toJson());
}
}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}
public static void update(){
try{
MongoCollection<Document> collection = getCollection("School","student");
collection.updateMany(Filters.eq("sname", "Mary"), new Document("$set",new Document("sage",22)));
System.out.println("更新成功!");
}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}
public static void delete(){
try{
MongoCollection<Document> collection = getCollection("School","student");
collection.deleteOne(Filters.eq("sname", "Bob"));
System.out.println("删除成功!");
}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}
}
|