比如我有一个user类,他包含一个标签属性,这个标签是一个数组,数组里面的元素是内嵌文档,格式如下:

{
    "_id" : "195861",
    "tags" : [
            {
                    "tagId" : NumberLong(766),
                    "optDate" : ISODate("2013-08-12T15:21:02.930Z"),
                    "enable" : true
            },
            {
                    "tagId" : NumberLong(778),
                    "optDate" : ISODate("2013-08-12T15:21:02.930Z"),
                    "enable" : true
            }
    ]

}

下面对这个文档中的tag进行增删该查操作,这里用到了spring mongodb 里面的MongoTemplate类。我这里把tags里的内嵌文档抽象成了Tag类。代码删除和修改本身就包含查询方法,所以没写查询方法

代码如下:

/**
 *
 * @author zhangdonghao
 *
 */
@Component("UserrTagServiceImpl")
public class UserrTagServiceImpl implements UserrTagService {

/**
 * Mongo DB Spring Template
 */
@Resource
protected MongoTemplate mongoTemplate = null;

public UserrTagServiceImpl() {

}
/**
**给tags数组添加一个元素
*/
@Override
public Response<Integer> addTag(String id, Long tagId) {

try {
        Tag tag = new Tag(tagId);
        tag.setOptDate(new Date());
        tag.setEnable(true);
        Query query = Query.query(Criteria.where("_id").is(id));
        Update update = new Update();
        update.addToSet("tags", tag);
        mongoTemplate.upsert(query, update, User.class);
    } catch (Exception e) {
        return new Response<Integer>(0);
    }
    return new Response<Integer>(1);
}

/**
**修改tags数组中内嵌文档指定一个元素的值
*/
@Override
public Response<Integer> disableTag(String id, Long tagId) {

try {
        Query query = Query.query(Criteria.where("_id").is(id)
                .and("tags.tagId").is(tagId));
        Update update = new Update();
        update.set("tags.$.enable", false);
        mongoTemplate.updateFirst(query, update, User.class);
    } catch (Exception e) {
        return new Response<Integer>(0);
    }
    return new Response<Integer>(1);
}
/**
**删除tags数组中指定的内嵌文档
*/
@Override
public Response<Integer> removeTag(String id, Long tagId) {

try {
        Query query = Query.query(Criteria.where("_id").is(id)
                .and("tags.tagId").is(tagId));
        Update update = new Update();
        update.unset("tags.$");
        mongoTemplate.updateFirst(query, update, User.class);
    } catch (Exception e) {
        return new Response<Integer>(0);
    }

return new Response<Integer>(1);
}

public MongoTemplate getMongoTemplate() {
    return mongoTemplate;
}

public void setMongoTemplate(MongoTemplate mongoTemplate) {
    this.mongoTemplate = mongoTemplate;
}
}

原文地址:https://www.linuxidc.com/Linux/2013-11/92408.htm

MongoDB对数组元素及内嵌文档进行增删改查操作的更多相关文章

  1. mongodb对数组元素及内嵌文档进行增删改查操作(转)

    from:https://my.oschina.net/132722/blog/168274 比如我有一个user类,他包含一个标签属性,这个标签是一个数组,数组里面的元素是内嵌文档,格式如下: &l ...

  2. mongodb的学习笔记一(集合和文档的增删改查)

    1数据库的增删改查 一.增加一个数据库: use blog-----切换到指定的数据库,如果数据库不存在,则自动创建该数据库(新建的数据库,如果没有存储对应的集合,是不会显示出来的) 二.删除一个数据 ...

  3. Elasticsearch之文档的增删改查以及ik分词器

    文档的增删改查 增加文档 使用elasticsearch-head查看 修改文档 使用elasticsearch-head查看 删除文档 使用elasticsearch-head查看 查看文档的三种方 ...

  4. 分布式搜索elasticsearch 索引文档的增删改查 入门

    1.RESTful接口使用方法 为了方便直观我们使用Head插件提供的接口进行演示,实际上内部调用的RESTful接口. RESTful接口URL的格式: http://localhost:9200/ ...

  5. Java对XML文档的增删改查

    JAVA增删改查XML文件   最近总是需要进行xml的相关操作. 不免的要进行xml的读取修改等,于是上网搜索,加上自己的小改动,整合了下xml的常用操作. 读取XML配置文件 首先我们需要通过Do ...

  6. head插件对elasticsearch 索引文档的增删改查

    1.RESTful接口使用方法 为了方便直观我们使用Head插件提供的接口进行演示,实际上内部调用的RESTful接口.  RESTful接口URL的格式: http://localhost:9200 ...

  7. Elasticsearch 索引文档的增删改查

    利用Elasticsearch-head可以在界面上(http://127.0.0.1:9100/)对索引进行增删改查 1.RESTful接口使用方法 为了方便直观我们使用Head插件提供的接口进行演 ...

  8. Mongodb的基本操作-数据库 集合 文档的增删改查

    数据库操作: //查看有哪些数据库 > show dbs local  0.078GB mydb   0.078GB //use操作将切换到一个数据库 如果数据库存在将直接切换 如果不存在 那么 ...

  9. elasticsearch java和_head插件对索引文档的增删改查

    利用head插件: 1,创建索引并添加一条数据(yananindex:索引名称,yanantype:索引类型,1:索引id) 2.修改索引数据(索引id1不变,_version是对该索引数据执行了几次 ...

随机推荐

  1. P2089 烤鸡

    题目背景 猪猪hanke得到了一只鸡 题目描述 猪猪Hanke特别喜欢吃烤鸡(本是同畜牲,相煎何太急!)Hanke吃鸡很特别,为什么特别呢?因为他有10种配料(芥末.孜然等),每种配料可以放1—3克, ...

  2. TCP学习

    参考 https://coolshell.cn/articles/11564.html https://coolshell.cn/articles/11609.html

  3. SQL和HQL 区别浅析!!!

    hql是面向对象查询,格式:from + 类名 + 类对象 + where + 对象的属性 sql是面向数据库表查询,格式:from + 表名 + where + 表中字段 1.查询 一般在hiber ...

  4. react 闲谈 之 JSX

    jsx元素-> React.createElement -> 虚拟dom对象 -> render方法 1.在react中想将js当作变了引入到jsx中需要使用{} 2.在jsx中,相 ...

  5. 前端知识点回顾之重点篇——CORS

    CORS(cross origin resource sharing)跨域资源共享 来源:http://www.ruanyifeng.com/blog/2016/04/cors.html 它允许浏览器 ...

  6. CPU排行-台式

    此文已经于2017年11月1日更新!来源于极速空间 实际对比: intel i3-7100(双核四线程) CPU性能远超过 AMD X4 860K(四核四线程) intel i5-7500(四核四线程 ...

  7. LC 975. Odd Even Jump

    You are given an integer array A.  From some starting index, you can make a series of jumps.  The (1 ...

  8. Handler处理消息

    UI主线程通过Looper循环查询消息队列UI_MQ,当发现有消息存在时会将消息从消息队列中取出.首先分析消息,通过消息的参数判断该消息对应的Handler,然后将消息分发到指定的Handler进行处 ...

  9. [Ubuntu]18安装navicat 破解版&官方版本

    破解版本: 一.下载破解版的navicat  链接:https://pan.baidu.com/s/1ulptSderoG0EbEQpO3Adww提取码:8oc3 二.解压到桌面 在下载压缩文件之后, ...

  10. CentOS 7 最小化安装后的注意事项

    http://blog.csdn.net/f_srion/article/details/54910943 在VM虚拟机中安装CentOS 7 时 有时候顾虑到电脑硬件性能,我们需要最小化安装,而最小 ...