MongonDB入门

MongonDB介绍

MongoDB 是一个基于分布式文件存储的数据库。由C++语言编写。旨在为WEB应用提供可扩展的高性能数据存储解决方案。MongoDB 是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的。他支持的数据结构非常松散,是类似json的bson格式,因此可以存储比较复杂的数据类型。Mongo最大的特点是他支持的查询语言非常强大,其语法有点类似于面向对象的查询语言,几乎可以实现类似关系数据库单表查询的绝大部分功能,而且还支持对数据建立索引。

MongonDB概念介绍

  • database mongon里面数据库的概念和其他关系型数据库一样,如mysql、oracle等

  • collection mongon里面collection类似于关系型数据库中的表,一类数据的集合,和其他数据库的区别就是数据库字段可以不固定

  • document mongon本身是面向文档的存储的介于关系与非关系型数据库,这里的document类似于mysql中的一条记录

  • field 数据库字段,和关系型数据一样

MongonDB使用

  • springboot

    • 添加pom依赖
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
    复制代码
    • 创建数据库实体
    @Document(collection = "user")    
    public class User {
    
        @Id
        private ObjectId id; //数据库id 与数据库字段_id对应,org.bson.types.ObjectId
    
        @Field(value = "user_name")
        private String username;
    
        @Field(value = "age")
        private Integer age;
    
        // 省略getter和setter
    }
    复制代码
    • 添加mongon配置
    spring:
        data:
            mongodb:
                host: localhost
                port: 26007
                database: test 
    复制代码
    • 创建repository
    public interface UserRepository extends MongoRepository<User, ObjectId>{
    }
    复制代码
    • 单元测试
    
    @RunWith(SpringJUnit4ClassRunner.class)
    @SpringApplicationConfiguration(Application.class)
    public class ApplicationTests {
    
        @Autowired
        private UserRepository userRepository;
    
        @Before
        public void setUp() {
            userRepository.deleteAll();
        }
    
        @Test
        public void test() throws Exception {
    
            // 创建user,并保存
            User user = new User();
            user.setAge(10)
            user.setUsername("hachel")
            userRepository.save(user);
          
            // 删除一个User,再验证User总数
            u = userRepository.findByUsername("hachel");
            userRepository.delete(u);
        
        }
    
    }
    复制代码

附录

转载于:https://juejin.im/post/5c6a0921e51d45403f2aa465

### MongoDB入门教程 MongoDB 是一种面向文档的 NoSQL 数据库,它使用 BSON(Binary JSON)格式存储数据,并支持灵活的模式设计。以下是 MongoDB 的基础知识: #### 1. 安装与配置 为了将 MongoDB 配置为服务,需要以管理员身份运行命令提示符并进入 MongoDB 的 `bin` 文件夹。例如: ```bash d: cd D:\MongoDB\Server\3.4\bin ``` 然后运行以下命令以安装 MongoDB 服务[^1]: ```bash mongod --bind_ip 0.0.0.0 --logpath D:\MongoDB\Server\3.4\data\logs\mongo.log --logappend --dbpath D:\MongoDB\Server\3.4\data\db --port 27017 --serviceName "MongoDB" --serviceDisplayName "MongoDB" --install ``` #### 2. 基本操作 - **插入数据**:可以使用 `insertMany` 方法向集合中插入多条数据。例如: ```javascript db.books.insertMany([{"userName":"Jack","age":20},{"userName":"Tom"}]); ``` 注意,MongoDB 中的代码是区分大小写的[^5]。 - **查询数据**:可以通过 `find` 方法查询集合中的数据。例如,查询所有由 "tutorials point" 发表且标题为 "MongoDB Overview" 的教程: ```javascript db.mycol.find({$or:[{"by":"tutorials point"},{"title": "MongoDB Overview"}]}).pretty(); ``` #### 3. 数据建模 在项目开发中,通常会使用 Mongoose 模块来定义数据模型和方法。例如,在 `stuModels.js` 文件中定义学生模型并暴露 `insert` 和 `query` 方法[^3]: ```javascript // 导入模块 var mongoose = require("mongoose"); // 连接数据库 const db = mongoose.createConnection('mongodb://shop2:123456@localhost:27017/shop', { useNewUrlParser: true, useUnifiedTopology: true }, err => { if (err) { console.log('数据库连接失败', err); return; } console.log('数据库连接成功'); }); // 设置数据类型 const model = db.model('stu', { name: { type: String, default: "zsr" }, age: { type: Number }, sex: { type: String } }); // 添加学生方法 const insert = postData => { const insertObj = new model(postData); return insertObj.save() .then(res => res) .catch(err => { console.log('插入失败' + err); return false; }); }; // 查询所有学生方法 const query = () => { return model.find() .then(res => res) .catch(err => { console.log('查询失败' + err); return false; }); }; // 导出方法 module.exports = { insert, query }; ``` #### 4. 聚合操作 MongoDB 提供了强大的聚合框架,用于执行复杂的分析任务。例如,通过 `$group` 对文档进行分组并计算总和[^4]: ```javascript db.collection_name.aggregate([ { $group: { _id: "$field", total: { $sum: "$value" } } } ]); ``` --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值