惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
云风的 BLOG
云风的 BLOG
美团技术团队
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
爱范儿
爱范儿
Stack Overflow Blog
Stack Overflow Blog
WordPress大学
WordPress大学
GbyAI
GbyAI
雷峰网
雷峰网
P
Proofpoint News Feed
IT之家
IT之家
人人都是产品经理
人人都是产品经理
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
aimingoo的专栏
aimingoo的专栏
小众软件
小众软件
T
The Blog of Author Tim Ferriss
月光博客
月光博客
V
Visual Studio Blog
L
LINUX DO - 热门话题
L
Lohrmann on Cybersecurity
T
Troy Hunt's Blog
Project Zero
Project Zero
U
Unit 42
T
Tor Project blog
Scott Helme
Scott Helme
L
LINUX DO - 最新话题
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
I
InfoQ
Cloudbric
Cloudbric
P
Proofpoint News Feed
The Cloudflare Blog
H
Heimdal Security Blog
Google DeepMind News
Google DeepMind News
The GitHub Blog
The GitHub Blog
Attack and Defense Labs
Attack and Defense Labs
有赞技术团队
有赞技术团队
T
Threat Research - Cisco Blogs
T
The Exploit Database - CXSecurity.com
J
Java Code Geeks
博客园 - 【当耐特】
Security Latest
Security Latest
The Register - Security
The Register - Security
F
Fortinet All Blogs
I
Intezer
H
Hackread – Cybersecurity News, Data Breaches, AI and More
MongoDB | Blog
MongoDB | Blog
N
Netflix TechBlog - Medium
NISL@THU
NISL@THU
T
Tenable Blog

风萧古道 - 勤学苦练,年复一年

游戏服务器开发经验(五)应对复杂需求 沉浸式体验东汉末年生活 - 《真三国无双 起源》玩后感 怒其不争!致2025年HLTV的Top18-NiKo Linux家用服务器维护指南 游戏服务器开发经验(四)避免写Bug的习惯、技巧和心态 游戏服务器开发经验(三)线上维护 游戏服务器开发经验(二)避免内存泄露 游戏服务器开发经验(一)道具防刷 35岁找不到工作,绝对不会是软件开发人员的结局 用爱发电项目开发两个月的心得体会 以魏延“子午谷奇谋”讨论软件需求可行性问题 MQTT协议中可变长度的具体计算方式(有计算过程解析) 关于游戏服务器配置表功能的探讨 Java并发编程中上锁的几种方式 如何用C++分割一个字符串? CSAPP第二章-信息的表示与处理 我的自我介绍 Windows XP虚拟机中文版无需激活下载 Java TreeSet的一些用法和特性 Linux C++ Socket实战 传统软件服务器与游戏服务器架构区别 独立个人项目开发心得 - 任务切分、挑战性、实用性和半途而废 使用Python实现简单UDP Ping 使用Python开发一个简单的web服务器 Kotlin手动实现一个最简单的哈希表 Kotlin实现二叉堆、大顶堆、优先级队列 搭建Spark实战环境(3台linux虚拟机集群)(一)样板机的搭建 Unison在Linux下的安装与使用 Java实现类似WINSCP访问远程Linux服务器,执行命令、上传文件、下载文件 一个被废弃的项目——自动爬取信息然后发给我自己邮箱上 Python连接MongoDB和Oracle实战 MongoDB常用查询语句 vue和springboot项目部署到Linux服务器 Python的一些用法(可能不定时更新) java正则表达式 - 双反斜杠(\)和Pattern的matches()与find() 简述爬虫对两种网站的不同爬取方式 Vue的路由配置及手动改地址栏为啥又跳转回来?? [JavaScript]JS基础知识 [Mybatis]逆向工程中Select语句查询不出‘TEXT’字段 [编译原理]FIRST、FOLLOW和SELECT [Spring]Spring学习笔记 [算法]分布估计算法 - 一种求解多维背包问题的混合分布估计算法_王凌 [日常]我做独立博客的原因 人间值得 深入理解计算机系统 想想就开心! 最重要的事,只有一件 藏书 被讨厌的勇气 关于 简历 朋友 尊重自己:给予与接收的心灵艺术
Springboot操作MongoDB,包括增改查及复杂操作
JonathanLin · 2020-05-19 · via 风萧古道 - 勤学苦练,年复一年

单条件查询

使用BasicDBObject配置查询条件

    List<AbstractMongoEntity> list = Lists.newArrayList();
    	// 配置查询条件
        BasicDBObject cond1 = new BasicDBObject();
        cond1.append("_id", new ObjectId("5de39f20684014f1d8b8fa37"));
        FindIterable<Document> findIterable = 
		// 执行查询
		mongoTemplate.getCollection("crawler_cjwt").find(cond1);
		// 装配查询结果
        MongoCursor<Document> cursor = findIterable.iterator();
        Document document = null;
        CjwtMongoEntity question = null;
        while (cursor.hasNext()) {
            document = cursor.next();
            // 使用MongoConverter可以将结果对象映射到Java Bean
            question = mongoConverter.read(CjwtMongoEntity.class, document);
            list.add(question);
        }
        System.out.println(question);
        cursor.close();

返回的是一个指针,所以我们需要通过该指针遍历结果,并装进list中返回使用。 对应的mongo脚本:

db.crawler_cjwt.find({'_id':new ObjectId("5de39f20684014f1d8b8fa37")})

查询该集合所有结果

        List<FgcxMongoEntity> list = Lists.newArrayList();
		// find函数没有传参,即查询所有
        FindIterable<Document> findIterable = crawlMongoTemplate.getCollection("fgcx").find();

        MongoCursor<Document> cursor = findIterable.iterator();
        FgcxMongoEntity question = null;
        while (cursor.hasNext()) {
            question = mongoConverter.read(FgcxMongoEntity.class, cursor.next());
            list.add(question);
        }
        cursor.close();

多条件查询

  String cityClassifyId = "b2c7147e804b48f8af562fbe1f1c32f6";
		// 上面这部分是获取省,市的名字
        IndustryRepoClassify cityClassify = industryRepoClassifyMapper.selectByPrimaryKey(cityClassifyId);
        IndustryRepoClassify provinceClassify = industryRepoClassifyMapper.selectByPrimaryKey(cityClassify.getParentId());
        IndustryRepoClassify bsznClassify = industryRepoClassifyMapper.selectByPrimaryKey(provinceClassify.getParentId());
        // 获取集合对象
        MongoCollection<Document> collection = mongoTemplate.getCollection("bszn");
     	// 配置查询BasicDBObject
        BasicDBObject filterCondition = new BasicDBObject();
        filterCondition.append("province.value", provinceClassify.getClassifyName());
        filterCondition.append("city.value", cityClassify.getClassifyName());
		// 执行查询
        FindIterable<Document> findIterable = collection.find(filterCondition);
        List<Document> res = (List<Document>) findIterable;

等价于Mongo脚本:

db.bszn.find({$and:[{'province.value': '某省份'}, {'city.value': '某城市'}]})

$in查询

 List<String> idList = Arrays.asList("5a08fea2704f44dda6e3d0a25d89014a", "96e71f036fa74bceac41130902f8d2be");
        BasicDBObject query = new BasicDBObject();
        BasicDBList conditionList = new BasicDBList();
        for (String id : idList) {
            conditionList.add(id);
        }
        // 在这里用$in做键,用上面定义的字符串数组为值
        query.put("classify_id", new BasicDBObject("$in", conditionList));
        FindIterable<Document> findIterable = mongoTemplate.getCollection("crawler_classify").find(query);
        MongoCursor<Document> cursor = findIterable.iterator();
        IndustryRepoClassify question = null;
        List<IndustryRepoClassify> list = Lists.newArrayList();
        while (cursor.hasNext()) {
            question = mongoConverter.read(IndustryRepoClassify.class, cursor.next());
            list.add(question);
        }
        cursor.close();

等价于Mongo脚本:

db.crawler_classify.find({'classify_id': 
{$in:['5a08fea2704f44dda6e3d0a25d89014a', '96e71f036fa74bceac41130902f8d2be']}})

更新某个属性

 	Bson filter = new BasicDBObject().append("_id", new ObjectId("5def5b6d5f090d15618df344"));
    BasicDBObject set = new BasicDBObject();
    set.append("kobe.value","33,");
    Bson update =  new Document("$set",set);
    crawlMongoTemplate.getCollection("test").updateOne(filter, update);

等价于Mongo脚本:

db.test.update({'_id': new ObjectId("5def5b6d5f090d15618df344")}, {$set:{'kobe.value':'33,'}},{})

用于接取Mongo数据的Java Bean定义注意事项

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import lombok.*;
import org.bson.types.ObjectId;
import org.springframework.data.mongodb.core.mapping.Field;
import java.util.List;
import java.util.Map;

/**
 * @Date: 2019/12/11 17:37
 */
@Data
@Getter
@Setter
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class CjwtMongoEntity {
    /**
     * mongoid
     */
    private ObjectId id;
    /**
     * url
     */
    @Field
    private Map url;
    /**
     * 数据来源
     */
    @Field
    private Map source;
    /**
     * 数据采集时间
     */
    @Field
    private Map time;
    /**
     * 批次号
     */
    @Field("batch_number")
    private Map batchNumber;
    /**
     * 省份
     */
    @Field
    private Map province;
    /**
     * 数据来源 人为添加:artificial 爬虫添加 crawler
     */
    @Field("data_source")
    private Map dataSource;
}

注意的点有两个,一是id直接定义为ObjectId类型就可以了,二是其他的属性需要与Mongo文档中对应,如果不是完全一致,则需要在@Field注解后面加上Mongo文档中的键名。