Write the Code. Change|

Kang_kin

园龄:4年4个月粉丝:2关注:9

2023-05-18 14:00阅读: 40评论: 0推荐: 0

Mongodb基本使用

python

  • 引入依赖

pip3 install pymongo

  • 连接Mongodb
import pymongo

client = pymongo.MongoClient(host='127.0.0.1', port=27017)
col = client['go']

spring

  • 导入依赖
<dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
  • yml配置
spring:
data:
  mongodb:
    host: 127.0.0.1
    port: 27017
    database: go
  • 实体类映射
/**
* @Document:该注解用于声明一个类为MongoDB的文档对象,并指定存储该对象所使用的集合名。
* @MongoId:该注解用于标识一个属性为MongoDB文档对象的主键,可以是任意类型(如String、Long等)
* @Field:该注解用于标识一个属性在MongoDB中对应的字段名,如果不指定则默认为属性名。
* @Transient:该注解用于标识一个属性不需要被持久化到MongoDB中。
**/
@Data
@Document("test002")
public class Test {
  @MongoId
  private String _id;
  @Field
  private String name;

  private String hometown;

  private double age;

  private String sex;

Mongodb语法

插入数据

插入一条数据

db.student.insert({
    "id": 20170101,
    "name": "Kang",
    "age": 18,
    "gender": "male"
})
# 当集合没有时会自己创建

插入多条数据

db.student.insertMany([{
  "id":20170101,
  "name":"Kang",
  "age":18,
  "gender":"male"  
},
{
  "id":20170102,
  "name":"Mike",
  "age":100,
  "gender":"male"  
}])

查询数据

# 查询一条记录
db.student.findOne({"name":"Kang"})

# 查询多条记录
db.student.find({"name":"Kang"})

# 查询age大于20的
db.student.find({"age":{"$gt":20}})

符号

符号 含义 实例
$lt 小于 db.student.find({age:{$lt:20}})
$gt 大于 db.student.find({age:{$gt:20}})
$lte 小于等于 db.student.find({age:{$lte:20}})
$gte 大于等于 db.student.find({age:{$gte:20}})
$ne 不等于 db.student.find({age:{$ne:20}})
$in 在范围内 db.student.find({age:{$in:[20,100]}})
$nin 不在范围内 db.student.find({age:{$nin:[20,100]}})

功能符号

符号 含义 实例
$regex 匹配正则表达式 db.student.find({name: {$regex: '^K.*'}}) name以K为开头
$exists 属性是否存在 db.student.find({name: {$exists: true}}) 存在name属性
$type 类型判断 db.student.find({name: {$type: 'string'}}) type的类型为string
$mod 数字模操作 db.student.find({age: {$mod: [5,0]}}) age的模5余0
$text 文本查询 db.student.find({ $text: { $search: "Kang" } }) Kang的字符串(需要建立索引)
$where 高级条件查询 db.collection.find({ $where: <JavaScript 表达式> }) 用于在查询中执行 JavaScript 表达式

计数(count)

db.student.find().count()
# 查询符合条件的数量

排序

db.student.find().sort({age:-1})   # 根据年龄降序
# db.collection.find().sort({ field1: 1, field2: -1 })
# collection 是你要查询的集合名称,field1 和 field2 是要排序的字段。1 表示按升序排序,-1 表示按降序排序。

偏移

db.collection.find().skip(offset)
# 使用 skip() 方法来实现偏移(offset)功能。skip() 方法用于跳过指定数量的文档,

db.student.find().skip(1)
# 跳过1个元素

更新

# 更新单个元素
db.collection.updateOne(
  { <查询条件> },
  { $set: { <更新字段1>: <更新值1>, <更新字段2>: <更新值2>, ... } }
)

# 满足第一个匹配的文档
db.student.updateOne({
    name: "Kang"
}, {
    $set: {
        age: 17
    }
})

# 满足多个匹配的元素
# 更新多个元素
db.collection.updateMany(
  { <查询条件> },
  { $set: { <更新字段1>: <更新值1>, <更新字段2>: <更新值2>, ... } }
)

删除

# 删除单个元素
db.collection.deleteOne({ <查询条件> })

# 删除多个元素
db.collection.deleteMany({ <查询条件> })

MongodbTemplate

查询

普通查询

@RestController
@RequestMapping("/one")
@Slf4j
public class OneController {

    @Autowired
    private MongoTemplate mongoTemplate;

    @RequestMapping("find")
    public void oneTest(){
       // 列表查询
        List<Test> all = mongoTemplate.findAll(Test.class);
      
     	//返回第一个查询内容
      Test one = mongoTemplate.findOne(null, Test.class);
        log.debug("{}",all);
    }
}

条件查询

  1. 等于(Equals)条件查询:
Criteria criteria = Criteria.where("fieldName").is(value);
Query query = Query.query(criteria);
List<Person> result = mongoTemplate.find(query, Person.class);
  1. 不等于(Not Equals)条件查询:
Criteria criteria = Criteria.where("fieldName").ne(value);
Query query = Query.query(criteria);
List<Person> result = mongoTemplate.find(query, Person.class);
  1. 大于(Greater Than)条件查询:
Criteria criteria = Criteria.where("fieldName").gt(value);
Query query = Query.query(criteria);
List<Person> result = mongoTemplate.find(query, Person.class);
  1. 小于(Less Than)条件查询:
Criteria criteria = Criteria.where("fieldName").lt(value);
Query query = Query.query(criteria);
List<Person> result = mongoTemplate.find(query, Person.class);
  1. 包含(In)条件查询:
Criteria criteria = Criteria.where("fieldName").in(values);
Query query = Query.query(criteria);
List<Person> result = mongoTemplate.find(query, Person.class);
  1. 逻辑与(And)条件查询:
Criteria criteria = new Criteria();
criteria.and("fieldName1").is(value1);
criteria.and("fieldName2").is(value2);
Query query = Query.query(criteria);
List<Person> result = mongoTemplate.find(query, Person.class);
  1. 分页查询: 分页查询可以使用skip()limit()方法结合查询条件来实现。skip()用于指定跳过的文档数量,limit()用于指定返回的文档数量。
int pageNo = 1; // 当前页码
int pageSize = 10; // 每页数量

Query query = new Query().skip((pageNo - 1) * pageSize).limit(pageSize);
List<Person> result = mongoTemplate.find(query, Person.class);
  1. 聚合查询: 聚合查询是使用MongoDB的聚合管道(Aggregation Pipeline)来执行多个聚合操作。可以使用Aggregation类和聚合操作符来构建聚合查询。
javaCopy code
Aggregation aggregation = Aggregation.newAggregation(
    Aggregation.match(Criteria.where("field").is(value)),
    Aggregation.group("field").count().as("count"),
    Aggregation.sort(Sort.Direction.DESC, "count"),
    Aggregation.limit(10)
);

AggregationResults<ResultType> results = mongoTemplate.aggregate(aggregation, "collectionName", ResultType.class);
List<ResultType> result = results.getMappedResults();

通过match()方法筛选出符合条件的文档,然后使用group()方法对指定字段进行分组统计,再通过sort()方法对统计结果进行排序,最后使用limit()方法限制返回结果的数量。

新增

save()

  • 如果保存的对象已经存在于数据库中(通过对象的_id字段判断),则会更新现有文档。
  • 如果保存的对象不存在于数据库中(通过对象的_id字段判断),则会将对象插入为新的文档。
javaCopy code
Person person = new Person("John", 25);
mongoTemplate.save(person);  // 如果person对象没有_id字段,则插入为新文档;如果person对象有_id字段,则更新现有文档

insert()

  • 如果保存的对象已经存在于数据库中(通过对象的_id字段判断),则会抛出DuplicateKeyException异常。
  • 如果保存的对象不存在于数据库中(通过对象的_id字段判断),则会将对象插入为新的文档。
javaCopy code
Person person = new Person("John", 25);
mongoTemplate.insert(person);  // 如果person对象没有_id字段,则插入为新文档;如果person对象有_id字段,并且存在于数据库中,则抛出异常
  • 总结:

  • save()方法可以用于新增或更新数据,根据对象的_id字段判断操作。

  • insert()方法用于新增数据,如果对象的_id字段已存在于数据库中,则会抛出异常。

更新

Query query = new Query(Criteria.where("name").is("John"));
Update update = new Update();
update.set("age",18);
// 更新匹配到的第一个
mongoTemplate.updateFirst(query, update, Test.class);

// 更新匹配到的所有
mongoTemplate.updateMulti(query, update, Test.class);

删除

// 根据条件删除
Query query = new Query(Criteria.where("name").is("John"));
mongoTemplate.remove(query, Person.class);

Redis-Mongodb

新增

student={
    "id": 20170101,
    "name": "Kang",
    "age": 18,
    "gender": "male"
}
# 新增一条数据
col.insert_one(student)

# 新增多条数据
col.insert_many([student,student])

查询

from bson.objectid import ObjectId

# 查询单个结果
col.find_one({'name':'Kang'})

# 根据_id查询
col.find_one({'_id':ObjectId('6465977ab873e5d4ea0a4861')})

# 查询大于20岁
col.find({'age':{'$gt':20}})

# 根据正则匹配查询
col.find({'name':{'$regex':'^M.*'}})

# 计数
col.find({'name':'Kang'}).count()

# 排序
col.find().sort('name',pymongo.ASCENDING)
# DESCENDING(降序)  ASCENDING(降序)

# 偏移
col.find().sort('name',pymongo.ASCENDING).skip(2)

更新

condition={'name':'K'}
stu = col.find(condition)
stu['age']=18

# 更新的条件   更新后的数据
col.update(condition,stu)

col.update(condition,{'$set':stu })

删除

# 删除一个
col.delete_one({'name':'K'})

# 删除多个
col.delete_many({'age':{'&gt':18}})

本文作者:Kang_kin

本文链接:https://www.cnblogs.com/kangkin/p/17411740.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   Kang_kin  阅读(40)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 记一次.NET内存居高不下排查解决与启示
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起