mongodb查询文档内部属性以及数组

本文涉及的产品
云数据库 MongoDB,通用型 2核4GB
简介: mongodb查询文档内部属性以及数组

1.mongodb——查询文档内部属性以及数组

文档格式:

 "mapData": {
                "children": [
                    {
                        "expectedYear": 2021,
                        "gender": 1,
                        "dob": "2010-10-10",
                        "name": "Alice",
                        "expectedGrade": "g1"
                    },
                    {
                        "expectedYear": 2021,
                        "gender": 1,
                        "dob": "2014-10-10",
                        "name": "Tom",
                        "expectedGrade": "g1"
                    }
                ],
                "scheduleId": 12,
                "contacts": [
                    {
                        "phone": "137222",
                        "name": "Elbem",
                        "email": "aab@niub.com"
                    },
                    {
                        "phone": "1373322",
                        "name": "Tonny",
                        "email": "aabc@niub.com"
                    }
                ],
                "status": 10
            },
            "formCategory": null,
            "creatorId": 4,
            "creatorType": "alpha",
            "campusId": 1,
            "tenantId": 1,
            "delFlag": 0
        }

查询方式:

        
    Query query = new Query();
    query.addCriteria(Criteria.where("mapData.scheduleId").in(ids));
    if(status == -3){//不等于-3的时候按照状态获取
      log.info("no status ",status);
    }else{
      //等于-3的时候获取全部
      query.addCriteria(Criteria.where("mapData.status").in(status));
    }
 
    int totalSum = Integer.valueOf(mongoTemplate.count(query, CustomFormMongoEntity.class, MongoUtils.getTenantCollName(ParentPrivateController.COLLECTION_NAME))+"");
    query.skip((page.getCurrent()-1)*page.getSize()).limit(Integer.valueOf(page.getSize()+""));

2.让mongoDB也能使用in查询

Query query = new Query();
//Criteria c = new Criteria();
query.addCriteria(Criteria.where("bid").in(ids));
sum = Integer.valueOf(mongoTemplate.count(query, BookChapterMongo.class)+"");

3.mongodb中使用$in和$all的区别$or操作符$and操作符

需求1:

查询出包含1或者包含4的数据

db.user.find({ id : { $in : [“1”,“4”] } } );

查询得到:

需求2:

查询出同时包含4和5的数据,这时就不能使用i n 来 进 行 查 询 了 , 因 为 i n 只 能 查 询 单 值 , 但 在 m o n g o d b 中 还 存 在 in来进行查询了,因为in只能查询单值, 但在mongodb中还存在in来进行查询了,因为in只能查询单值,但在mongodb中还存在all操作符,用于查询整个

db.user.find( { id: { $all:[“4”,“5”] } } )

得到结果:

总结:in只能查不重复的all可以查重复的。

4.mongodb查询的语法(大于,小于,大于或等于,小于或等于等等)

1 ) . 大于,小于,大于或等于,小于或等于


$gt:大于

$lt:小于

$gte:大于或等于

$lte:小于或等于


例子:


db.collection.find({ "field" : { $gt: value } } ); // greater than : field > value

db.collection.find({ "field" : { $lt: value } } ); // less than : field < value

db.collection.find({ "field" : { $gte: value } } ); // greater than or equal to : field >= value

db.collection.find({ "field" : { $lte: value } } ); // less than or equal to : field <= value

如查询j大于3,小于4:

db.things.find({j : {$lt: 3}});

db.things.find({j : {$gte: 4}});

也可以合并在一条语句内:

db.collection.find({ "field" : { $gt: value1, $lt: value2 } } ); // value1 < field < value

2) 不等于 $ne

例子:

db.things.find( { x : { $ne : 3 } } );



3) in 和 not in ($in $nin)


语法:

db.collection.find( { "field" : { $in : array } } );

例子:

db.things.find({j:{$in: [2,4,6]}});

db.things.find({j:{$nin: [2,4,6]}});



4) 取模运算$mod


如下面的运算:

db.things.find( "this.a % 10 == 1")

可用$mod代替:

db.things.find( { a : { $mod : [ 10 , 1 ] } } )



5) $all


$all和$in类似,但是他需要匹配条件内所有的值:


如有一个对象:


{ a: [ 1, 2, 3 ] }

下面这个条件是可以匹配的:

db.things.find( { a: { $all: [ 2, 3 ] } } );

但是下面这个条件就不行了:

db.things.find( { a: { $all: [ 2, 3, 4 ] } } );


6) $size


$size是匹配数组内的元素数量的,如有一个对象:{a:["foo"]},他只有一个元素:


下面的语句就可以匹配:db.things.find( { a : { $size: 1 } } );

官网上说不能用来匹配一个范围内的元素,如果想找$size<5之类的,他们建议创建一个字段来保存元素的数量。

You cannot use $size to find a range of sizes (for example: arrays with more than 1 element). If you need to query for a range, create an extra size field that you increment when you add elements.

7)$exists

$exists用来判断一个元素是否存在:

如:

db.things.find( { a : { $exists : true } } ); // 如果存在元素a,就返回

db.things.find( { a : { $exists : false } } ); // 如果不存在元素a,就返回


8) $type


$type 基于 bson type来匹配一个元素的类型,像是按照类型ID来匹配,不过我没找到bson类型和id对照表。

db.things.find( { a : { $type : 2 } } ); // matches if a is a string

db.things.find( { a : { $type : 16 } } ); // matches if a is an int

9)正则表达式


mongo支持正则表达式,如:


db.customers.find( { name : /acme.*corp/i } ); // 后面的i的意思是区分大小写


10) 查询数据内的值


下面的查询是查询colors内red的记录,如果colors元素是一个数据,数据库将遍历这个数组的元素来查询。db.things.find( { colors : "red" } );


11) $elemMatch


如果对象有一个元素是数组,那么$elemMatch可以匹配内数组内的元素:


> t.find( { x : { $elemMatch : { a : 1, b : { $gt : 1 } } } } )

{ "_id" : ObjectId("4b5783300334000000000aa9"),

"x" : [ { "a" : 1, "b" : 3 }, 7, { "b" : 99 }, { "a" : 11 } ]

}$elemMatch : { a : 1, b : { $gt : 1 } } 所有的条件都要匹配上才行。

注意,上面的语句和下面是不一样的。

> t.find( { "x.a" : 1, "x.b" : { $gt : 1 } } )

$elemMatch是匹配{ "a" : 1, "b" : 3 },而后面一句是匹配{ "b" : 99 }, { "a" : 11 }



12) 查询嵌入对象的值


db.postings.find( { "author.name" : "joe" } );

注意用法是author.name,用一个点就行了。更详细的可以看这个链接: dot notation

举个例子:

> db.blog.save({ title : "My First Post", author: {name : "Jane", id : 1}})

如果我们要查询 authors name 是Jane的, 我们可以这样:

> db.blog.findOne({"author.name" : "Jane"})

如果不用点,那就需要用下面这句才能匹配:

db.blog.findOne({"author" : {"name" : "Jane", "id" : 1}})

下面这句:

db.blog.findOne({"author" : {"name" : "Jane"}})

是不能匹配的,因为mongodb对于子对象,他是精确匹配。

13) 元操作符 $not 取反

如:

db.customers.find( { name : { $not : /acme.*corp/i } } );db.things.find( { a : { $not : { $mod : [ 10 , 1 ] } } } ); mongodb还有很多函数可以用,如排序,统计等,请参考原文。

 

5.mongodb根据_id删除

@GetMapping("/id")
  //@PreAuthorize("@pms.hasPermission('eaorg_vstbooked_del')")
  public R removeById(@RequestParam(value = "id") String id) {
 
    Query query=new Query(Criteria.where("_id").is(id));
    long count = mongoTemplate.remove(query,Map.class,"集合名称").getDeletedCount();
    return R.ok(count);
 
    //return R.ok(vstBookedService.removeById(id));
  }

6.mongodb根据_id修改

public R updateById(@RequestBody CustomFormMongoEntity visitBookMongoEntity) {
    Query query = new Query();
    query.addCriteria(Criteria.where("_id").is(visitBookMongoEntity.getId()));
 
    Document doc = new Document();
    mongoTemplate.getConverter().write(visitBookMongoEntity,doc);
    Update update = Update.fromDocument(doc,"_id");
    UpdateResult upsert = mongoTemplate.upsert(query, update, MongoUtils.getTenantCollName(ParentPrivateController.COLLECTION_NAME));
 
    //return R.ok(vstBookedService.updateById(vstBooked));
    return R.ok(upsert);
  }

7.mongodb根据添加

mongoTemplate.save(visitBookMongoEntity,"集合名称")

8.mongodb分页

Query query = new Query();
    query.addCriteria(Criteria.where("mapData.scheduleId").in(ids));
    if(status == -3){/
      log.info("no status ",status);
    }else{
      
      query.addCriteria(Criteria.where("mapData.status").in(status));
    }
 
    int totalSum = Integer.valueOf(mongoTemplate.count(query, CustomFormMongoEntity.class, MongoUtils.getTenantCollName(ParentPrivateController.COLLECTION_NAME))+"");
    query.skip((page.getCurrent()-1)*page.getSize()).limit(Integer.valueOf(page.getSize()+""));
    List<CustomFormMongoEntity> customFormMongoEntities = mongoTemplate.find(query, CustomFormMongoEntity.class, MongoUtils.getTenantCollName(ParentPrivateController.COLLECTION_NAME));
    page.setRecords(customFormMongoEntities);
    page.setTotal(totalSum);
    return R.ok(page);
相关实践学习
MongoDB数据库入门
MongoDB数据库入门实验。
快速掌握 MongoDB 数据库
本课程主要讲解MongoDB数据库的基本知识,包括MongoDB数据库的安装、配置、服务的启动、数据的CRUD操作函数使用、MongoDB索引的使用(唯一索引、地理索引、过期索引、全文索引等)、MapReduce操作实现、用户管理、Java对MongoDB的操作支持(基于2.x驱动与3.x驱动的完全讲解)。 通过学习此课程,读者将具备MongoDB数据库的开发能力,并且能够使用MongoDB进行项目开发。 &nbsp; 相关的阿里云产品:云数据库 MongoDB版 云数据库MongoDB版支持ReplicaSet和Sharding两种部署架构,具备安全审计,时间点备份等多项企业能力。在互联网、物联网、游戏、金融等领域被广泛采用。 云数据库MongoDB版(ApsaraDB for MongoDB)完全兼容MongoDB协议,基于飞天分布式系统和高可靠存储引擎,提供多节点高可用架构、弹性扩容、容灾、备份回滚、性能优化等解决方案。 产品详情: https://www.aliyun.com/product/mongodb
相关文章
|
1天前
|
NoSQL 关系型数据库 MySQL
深入了解 Python MongoDB 查询:find 和 find_one 方法完全解析
在 MongoDB 中,我们使用 find() 和 find_one() 方法来在集合中查找数据,就像在MySQL数据库中使用 SELECT 语句来在表中查找数据一样
67 1
|
1天前
|
NoSQL 测试技术 定位技术
【MongoDB 专栏】MongoDB 的地理空间索引与位置查询
【5月更文挑战第10天】MongoDB 支持地理空间数据处理,提供2dsphere(球面)和2d(平面)索引,适用于地图导航、物流、社交网络等领域。通过创建索引,可加速位置查询,如查询范围、最近邻及地理空间聚合。案例包括地图应用、物流追踪和社交网络。注意数据准确性、索引优化和性能测试,以发挥其在地理空间处理中的潜力。学习此功能,为应用开发解锁更多可能性!
【MongoDB 专栏】MongoDB 的地理空间索引与位置查询
|
1天前
|
存储 NoSQL 数据管理
【MongoDB 专栏】MongoDB 文档模型详解
【5月更文挑战第10天】MongoDB 是一种流行的 NoSQL 数据库,以其灵活的文档数据模型著称。文章介绍了文档的基本概念、结构及操作,包括插入、查询、更新和删除。文档特点是灵活且可扩展,适合存储不同结构的数据。优势在于简化数据建模、提升开发效率并适应动态数据。应用场景包括用户信息、日志记录和电商数据管理。但需注意数据一致性和文档大小对性能的影响。理解文档模型有助于高效利用 MongoDB。
【MongoDB 专栏】MongoDB 文档模型详解
|
1天前
|
NoSQL 数据处理 MongoDB
MongoDB查询操作深度剖析
【4月更文挑战第30天】本文深入探讨了MongoDB查询操作,包括查询语法、优化及高级技巧。使用`find()`方法进行查询,如`db.users.find({ age: { $gt: 25 } })`找年龄大于25的用户。优化查询性能涉及创建索引、使用复合索引和避免全表扫描。高级查询涵盖聚合管道、文本搜索和地理空间查询,提供复杂数据处理和地理位置查询能力。理解并应用这些知识能提升MongoDB的使用效率和应用性能。
|
1天前
|
存储 NoSQL MongoDB
MongoDB数据模型与文档结构详解
【4月更文挑战第30天】MongoDB是一个基于文档的NoSQL数据库,其数据模型由文档(类似键值对集合,支持嵌套和数组)、集合(无需预定义结构的文档组)和数据库(包含集合的组织单元)构成。文档使用BSON格式,支持多种数据类型。在设计数据模型时,应注意避免过度嵌套,利用索引优化查询,并考虑数据生命周期。MongoDB通过引用处理文档间关系,提供灵活性以适应复杂数据结构。
|
1天前
|
存储 JSON DataWorks
DataWorks产品使用合集之DataWorks将 MongoDB 中的数组类型写入到 DataWorks 的单个字段时,表示为字符串格式而非 JSON 格式如何解决
DataWorks作为一站式的数据开发与治理平台,提供了从数据采集、清洗、开发、调度、服务化、质量监控到安全管理的全套解决方案,帮助企业构建高效、规范、安全的大数据处理体系。以下是对DataWorks产品使用合集的概述,涵盖数据处理的各个环节。
26 3
|
1天前
|
存储 JSON NoSQL
MongoDB的文档存储格式BSON和JSON的区别
MongoDB的文档存储格式BSON和JSON的区别
|
1天前
|
JSON NoSQL MongoDB
mongodb导出聚合查询的数据
mongodb导出聚合查询的数据
|
1天前
|
NoSQL MongoDB
mongodb分组查询
mongodb分组查询
http://www.vxiaotou.com