安装mongodb
https://blog.youkuaiyun.com/weixin_39739846/article/details/110856011
mongo -version 查看mongo版本
sudo service mongod start #启动mongo
sudo service mongod stop #关闭mongo
sudo service mongod restart #重启mongo
Shell
show dbs #显示数据库列表
show collections #显示当前数据库中的集合(类似关系数据库中的表table)
show users #显示所有用户
use yourDB #切换当前数据库至yourDB,如果数据库不存在,则创建数据库
#MongoDB没有单独创建集合名的shell命令,在插入数据的时候,MongoDB会自动创建对应的集合。
db.COLLECTION_NAME.insert(document)
#e.g.
db.student.insert(
{
'name': 'lisi',
'score': {
'English': 55,
'Math': 100,
'Computer': 88
}
}
);
#查询方法
db.COLLECTION_NAME.find(条件,返回结果)
#e.g.
db.student.find({name:"zhangsan"},{"_id":0,"score":1});#0表示不返回,1表示返回
# 查询worker集合中name属性是"majinqiao"的数据
# pretty函数 ,以格式化的方式显示查询结果
db.worker.find({name:"majinqiao"}).pretty()
# or查询 name = "majinqiao" or score = 54
db.worker.find({$or:[{name:"majinqiao"},{score:54}]}).pretty()
# or查询 age < 30 or age > 50
db.worker.find({$or:[{age:{$lt:30}},{age:{$gt:50}}]})
# or查询 age <= 30 or age => 50
db.worker.find({$or:[{age:{$lte:30}},{age:{$gte:50}}]})
# and查询 age != 30 and name != 'chengya'
db.worker.find({age:{$ne:30},age:{$ne:50}})
# and查询,name = "majinqiao" and age = 36
db.worker.find({name:"majinqiao",age:36}).pretty()
# 查找name字段为字符串的数据
db.worker.find({name:{$type:"string"}})
# 限制查询结果条数为2条
db.worker.find({name:"zhangjian"}).limit(2)
# province字段正序排列,city_age字段倒序排列
db.city.find().sort({province:1,city_age:-1})
# 当limit,skip,sort同时出现时,逻辑顺序为sort,skip,limit
db.worker.find({name:"zhangjian"}).limit(2).skip(1).sort({score:1})
# 查询city集合中存在history字段,且history的值是null的数据
db.city.find({history:{$in:[null],$exists:true}})
# select _id,city_name as cityName from city where city_name = 'jingzhou' and city_age >= 10
# _id 是默认查询的,如果想不返回这个字段, _id:0 即可
db.city.find({city_name:"jingzhou",city_age:{$gte:10}},{cityName:"$city_name"})
Java
导入依赖项
导入依赖或引入jar包
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.12.11</version>
</dependency>
连接数据库和集合
MongoClient mongoClient = new MongoClient("localhost", 27017);
MongoDatabase database = mongoClient.getDatabase("test"); //数据库
MongoCollection<Document> student = database.getCollection("student"); //集合
插入数据
public static void main(String[] args) {
MongoClient mongoClient = new MongoClient("localhost", 27017);
MongoDatabase database = mongoClient.getDatabase("test");
MongoCollection<Document> student = database.getCollection("student");
Document score = new Document("English",45).append("Math",89).append("Computer",100);
Document doc = new Document("name","scofield").append("score",score);
student.insertOne(doc);
}
查询数据
public static void main(String[] args) {
MongoClient mongoClient = new MongoClient("localhost", 27017);
MongoDatabase database = mongoClient.getDatabase("test");
MongoCollection<Document> student = database.getCollection("student");
FindIterable<Document> iterable = student.find(new BasicDBObject("name","scofield"));
for(Document doc : iterable){
System.out.println(doc.get("score"));
}
}
https://blog.youkuaiyun.com/yangning5850/article/details/18738651
旧版API
连接数据库
import com.mongodb.MongoClient;
……//这里省略其他需要导入的包
public class MongoDBJDBC{
public static void main( String args[] ){
try{
// 连接到 mongodb 服务
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
// 连接到数据库
DB db = mongoClient.getDB( "test" );
System.out.println("Connect to database successfully");
boolean auth = db.authenticate(myUserName, myPassword);
System.out.println("Authentication: "+auth);
}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}
}
创建集合
可以使用com.mongodb.DB类中的createCollection()来创建集合
public class MongoDBJDBC{
public static void main( String args[] ){
try{
// 连接到 mongodb 服务
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
// 连接到数据库
DB db = mongoClient.getDB( "test" );
System.out.println("Connect to database successfully");
boolean auth = db.authenticate(myUserName, myPassword);
System.out.println("Authentication: "+auth);
DBCollection coll = db.createCollection("mycol");
System.out.println("Collection created successfully");
}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}
}
插入文档
可以使用com.mongodb.DBCollection类的 insert() 方法来插入一个文档
public class MongoDBJDBC{
public static void main( String args[] ){
try{
// 连接到 mongodb 服务
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
// 连接到数据库
DB db = mongoClient.getDB( "test" );
System.out.println("Connect to database successfully");
boolean auth = db.authenticate(myUserName, myPassword);
System.out.println("Authentication: "+auth);
DBCollection coll = db.getCollection("mycol");
System.out.println("Collection mycol selected successfully");
BasicDBObject doc = new BasicDBObject("title", "MongoDB").
append("description", "database").
append("likes", 100).
append("url", "http://www.w3cschool.cc/mongodb/").
append("by", "w3cschool.cc");
coll.insert(doc);
System.out.println("Document inserted successfully");
}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}
}