MongoDB對數組元素及內嵌文檔進行增刪改查操作

來源:互聯網
上載者:User

比如我有一個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;
}
}

MongoDB 的詳細介紹:請點這裡
MongoDB 的:請點這裡

推薦閱讀:

Java實現MongoDB中自增長欄位

CentOS編譯安裝MongoDB

CentOS 編譯安裝 MongoDB與mongoDB的php擴充

CentOS 6 使用 yum 安裝MongoDB及伺服器端配置

Ubuntu 13.04下安裝MongoDB2.4.3

如何在MongoDB中建立新資料庫和集合

MongoDB入門必讀(概念與實戰並重)

《MongoDB 權威指南》(MongoDB: The Definitive Guide)英文文字版[PDF]

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.