mongodb

时间:2024-02-22 15:40:01
1.mongodb基本操作
1.mongodb的基本操作

mongod  -f D:/software/mongodb/mongodb/conf/mongo.conf --auth //以授权方式启动mongo

读写权限: read/readWrite 读写库的权限
数据库管理角色: dbAdmin 某数据库管理权限
userAdmin 某数据库用户的管理权限,包括创建用户,授权的管理
dbOwner 某数据库的所有者,拥有该库的所有权限,包括readWrite,dbAdmin和userAdmin权限
集群权限 :
备份和恢复角色: bakcup restore
所有数据库角色: readAnyDatabase
readWriteAnyDatabase
dbAdminAnyDatabase
userAdminAnyDatabase
超级用户角色: root

db.createUser({
    user: 'xm2',
    pwd: '123456',
    roles: [{
        role: 'readWrite',
        db: 'student'
    }]
});
db.auth('xm','123'); // 切换登录用户
show users;

mongo -uxm2 -p123456
use student
db.worker.find();
db.changeUserPassword("xm2","123");
db.currentOp();// 
db.dropUser('xm2');


show dbs; // 查看数据库
use student; 创建数据库
//创建表
db.createCollection("teacher", {
    capped:true,
    size: 10000
});
//插入数据
db.teacher.insertOne({
    "tno": 1,
    "tname": "123",
    "tage":20
});

db.createCollection("teacher");
//插入多条数据
db.teacher.insertMany([
    {
        "tno": 2,
        "tname": "124",
        "tage":21,
        "students":[106,107,108]
    },
    {
        "tno": 3,
        "tname": "125",
        "tage":22,
        "students":[107,108,109]
    }
]);
// 更新数据
db.teacher.update({
    "tname":"124"
},{
    $push: {
        "students":125
    }
})
db.teacher.find({"tname":"124"});
//com.mongodb.MongoWriteException: cannot remove from a capped collection: student.teacher
db.teacher.remove({"tno":123});//
db.teacher.find({});
show collections;
db.teacher.drop();
db.student.insert({
    "sno":101,
    "sname":"王五",
    "sage":20,
    "ssex":1,
    "hobby": ["吃饭","工作","睡觉"]
});

db.createCollection("weather", {
    timeseries: {
        timeField:"timestammp",
        metaField:"metadata",
        granularity:"hours"
    }
});
db.student.ensureIndex({"sno":1}, {unique:true});
db.student.insertOne({
    "sno":105,
    "sname":"zhaoliu",
    "sage":24,
    "ssex":1,
    "hobby":["工作","学习"]
});

--链接查询--
db.student.aggregate([
    {
        $match:{
            "sno":106
        }
    },
    {
        $lookup:{
            from:"teacher",
            localField:"students",
            foreignField:"sno",
            as:"result"
        }
    }
]);

db.student.find({
    "sno":106
});
db.student.find({
    "sname":"王五"
});

db.student.updateMany(
    {

        "sname":"zhangsan"

    },
    {

        $set: {
            "sage":20,
            "ssex":1,
            "hobby":["读书","写字"],
            "ssex":1
        }
    }
);
db.student.insertMany([{
    "sno":105,
    "sname":"zhaoliu",
    "sage":24,
    "ssex":1,
    "hobby":["工作","学习"]
},{
    "sno":106,
    "sname":"zhaoliu",
    "sage":23,
    "ssex":1,
    "hobby":["工作","学习"]
},{
    "sno":107,
    "sname":"zhaoliu",
    "sage":22,
    "ssex":1,
    "hobby":["工作","学习"]
}]);

db.student.updateMany({
    "sname":"zhaoliu"
},{
    $inc:{
        "sage":2
    }
});

db.student.find({
    "sname":"zhaoliu"
});

db.student.remove({
    "sname":"zhangsan"
});

db.student.find({
    "sage": {
        $gt:10,
        $lt:20
    },
    "sname":"zhaoliu",
    "sno": {
        $lte: 103
    }
});

# -1为降序, 1为升序
db.student.find({}).sort({"sage":-1}).limit(5).skip(2);
db.student.remove({});
db.student.getIndexes();
db.student.createIndex({
    "sno":1,
    unique:true

});
db.student.dropIndex("sno_1");

2.springboot 整合mongodb



<dependency>
      <groupId>org.mongodb</groupId>
      <artifactId>mongodb-driver-sync</artifactId>
      <version>3.12.8</version>
</dependency>
MongoClients 这个类在这个包里,自己写个原生的就这样玩
public class  MongoController{

    private static MongoClient client;

    static {
        if(client == null){
            synchronized (MongoClient.class){
                if(client == null){
                    client = MongoClients.create();
                }
            }
        }
    }

    public static void createCollection(String dataBaseName,String collectionName){
        MongoDatabase database = client.getDatabase(dataBaseName);
        database.createCollection(collectionName);
    }

    public static MongoCollection getCollection(String dataBaseName,String collectionName){
        MongoDatabase database = client.getDatabase(dataBaseName);
        MongoCollection collection= database.getCollection(collectionName);
        return collection;
    }

    public static void insertOne(MongoCollection collection,Document document){
        collection.insertOne(document);
    }

    public static void insertMany(MongoCollection collection, List<Document> documents){
        collection.insertMany(documents);
    }

    public static List<Document> createDocument(){
        List<Document> documents = new ArrayList<>();
        for(int i=1; i<100;i++){
            Document document = new Document();
            document.put("cityId",1L);
            if(i%4==0){
                document.put("cityName","上海市");
            }else if(i%4==1){
                document.put("cityName","北京市");
            }else if(i%4==2) {
                document.put("cityName","重庆市");
            }else {
                document.put("cityName","天津市");
            }
            documents.add(document);
        }
        return documents;
    }

    public static void main(String[] args) {
        Document document = new Document();
        document.put("cityId",1L);
        document.put("cityName","上海市");
        MongoCollection collection = getCollection("student", "city");
        insertOne(collection,document);
        insertMany(collection,createDocument());
        FindIterable  cities = collection.find();
        //cities.iterator().forEachRemaining(city ->System.out.println(city));
        Bson bson = Filters.eq("cityName", "上海市");
        //collection.deleteMany(bson);
        collection.find(Filters.eq("cityName","重庆"))
                .iterator().forEachRemaining(city->System.out.println());

        Document doc = new Document();
        doc.put("$set",new Document("desciption","好极了"));
        UpdateResult updateResult = collection.updateMany(Filters.eq("cityName", "天津"), doc);
        System.out.println(updateResult);
        FindIterable findIterable = collection.find(Filters.eq("cityName", "天津"));
        findIterable.iterator().forEachRemaining(city -> System.out.println(city));
    }
}

// 网上有个demon 使用persion 类但是我这个_id 不能mapping to cityName,乱七八糟的错,直接用人家的整合包完事。
class CityCodec implements Codec<City> {
    @Override
    public void encode(BsonWriter writer, City value, EncoderContext encoderContext) {
        writer.writeStartDocument();
        writer.writeInt64("cityId",value.getCityId());
        writer.writeInt64("provinceId",value.getProvinceId());
        writer.writeString("cityName", value.getCityName());
        writer.writeString("description", value.getDescription());
        writer.writeEndDocument();
    }

    @Override
    public Class<City> getEncoderClass() {
        return City.class;
    }

    @Override
    public City decode(BsonReader reader, DecoderContext decoderContext) {
        reader.readStartDocument();
        String cityName = reader.readString("cityName");
        Long provinceId = reader.readInt64("provinceId");
        String description = reader.readString("description");
        reader.readEndDocument();
        City city = new City();
        city.setCityName(cityName);
        city.setDescription(description);
        city.setProvinceId(provinceId);
        return city;
    }
}

mongodb 整合springboot
<dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-data-mongodb</artifactId>
       <version>${spring.boot.version}</version>
</dependency>
spring.data.mongodb.uri=mongodb://xm:123@127.0.0.1:27017/student?authSource=admin&authMechanism=SCRAM-SHA-1 //?后面这堆必须写上不然自己创建的用户无法登录

@EnableMongoRepositories
public class MailApplication {

}

@Repository
public interface PersonDao extends MongoRepository<Persion, String> {

}

@Document
@Data
public class Persion {
    @Id
    private String name;
    private Integer age;
}

3.mongodb的配置文件

# mongod.conf
# for documentation of all options, see:
#   http://docs.mongodb.org/manual/reference/configuration-options/
# Where and how to store data.
storage:
  dbPath: D:/software/mongodb/mongodb
  journal:
    enabled: true
#  engine:
#  mmapv1:
#  wiredTiger:
# where to write logging data.
systemLog:
  destination: file
  logAppend: true
  path: D:/software/mongodb/mongodb/logs/mongod.log
# network interfaces
net:
  port: 27017
  bindIp: 0.0.0.0
# how the process runs
#processManagement:
  #timeZoneInfo: /usr/share/zoneinfo
security:
   authorization: enabled
#operationProfiling:
#replication:
#sharding:
## Enterprise-Only Options:
#auditLog:
#snmp:

4.高级方面的问题mongodb 的storage engine,mongodb repliaction