---
title: "go语言中mongodb的子文档数组操作"
author: "zdrqq"
date: "2014-04-03T12:24:19Z"
tags: []
categories: ["编程语言"]
slug: "go-mongodb"
draft: false
lastmod: "2014-04-03T12:27:10Z"
id: 2040429
url: "https://senon.iteye.com/blog/2040429"
---

使用mongodb数据库的同学应该会经常遇到document中子文档数组的操作，开始没弄明白之前感觉挺费神，后来查了些资料，自己摸索了一下，特此记录下来，以供参考；  
本文描述的 Go语言 代码使用了labix.org/v2/mgo驱动  
假设有一个图文类News，它的内容包含了文字和图片，或者纯粹是多张图片，结构如下：

```
type News struct{
    Id int64 `bson:"_id"`
    Title string
    Content NewsContent
}

type NewsContent struct{
    Id int64
    Title string
    Content string
    Images []Image
    Type int
}

type Image struct{
    Id int64
    Url string
    Width int
    Height int
    Mark string
}
```

 

一个图文的内容可以包含很多张图片，那么后台发布图文的内容时，图片可能需要单独进行增删改操作，这就涉及到子文档数组的操作，类似下面代码:  
 

```
//AddNewsImg 增加图片
func (this *NewsDao) AddNewsImg(newsId int64, img *Image) (err error) {
    session := this.GetSession()
    query := bson.M{"_id": newsId}
    update := bson.M{"$push": bson.M{"content.images": img}}
    err = session .Update(query, update)
    return
}
```

 

```
//UpdateNewsImg 更新图片
func (this *NewsDao) UpdateNewsImg(newsId int64, img *Image) (err error) {
    session := this.GetSession()
    query := bson.M{"_id": newsId, "content.images.id": img.Id}
    update := bson.M{"$set": bson.M{"content.images.$": img}}
    err = session .Update(query, update)
    return
}
```

   
这里$符合代表当前找到的Image，然后使用set更新，也可以单独一项一项的更新，如：update := bson.M{"$set": bson.M{"content.images.$.url": img.Url,"content.images.$.width": img.Width}}

```
//DeleteNewsImg 删除图片
func (this *NewsDao) DeleteNewsImg(newsId int64, img *Image) (err error) {
    session := this.GetSession()
    query := bson.M{"_id": newsId}
    update := bson.M{"$pull": bson.M{"content.images": bson.M{"id": img.Id}}}
    err = session .Update(query, update)
    return
}
```

   
这里是按特殊条件进行删除的：update := bson.M{"$pull": bson.M{"content.images": bson.M{"id": img.Id}}} 其中bson.M{"id": img.Id}指的是按照数组中某一张图片的id进行删除；  
网上很多文章都是按整个对象进行删除，这样要求传入的img的每一项内容都必须与数据库中的一致才能删除成功，对于复杂点的对象显然不适用。