---
title: "mongo-embedded心得"
author: "andyjackson"
date: "2010-08-02T17:48:25Z"
tags: []
categories: ["编程语言"]
slug: "mongo-embedded"
draft: false
lastmod: "2010-08-02T17:48:25Z"
id: 727341
url: "https://ajwang.iteye.com/blog/727341"
---

大家都知道，mongo支持对embbeded的子项进行查询和更新操作，其实mongo从1.3.4之后支持对数组中的item为对象的进行查询和更新操作。

'$'符号是进行这类查询的基础。首先，我们要理解他的含义。  
 官方文档中说到：“The $ operator (by itself) means "position of the matched array item in the query".”该符号指的就是在制定的数组中匹配的item的位置，因此我们看到了希望。下面是它的例子：

```
> t.find()
{ "_id" : ObjectId("4b97e62bf1d8c7152c9ccb74"), "title" : "ABC",
  "comments" : [ { "by" : "joe", "votes" : 3 }, { "by" : "jane", "votes" : 7 } ] }

> t.update( {'comments.by':'joe'}, {$inc:{'comments.$.votes':1}}, false, true ) 
、**这句是指根据{'comments.by':'joe'}找到匹配的项，然后根据该项所在的位置将投票数增加1
> t.find()
{ "_id" : ObjectId("4b97e62bf1d8c7152c9ccb74"), "title" : "ABC",
  "comments" : [ { "by" : "joe", "votes" : 4 }, { "by" : "jane", "votes" : 7 } ] }
```

 “Currently the $ operator only applies to the **first** matched item in the query”，从这句话可知，它只会更新匹配到的第一个元素，而不是所有的元素。

```
> t.find();
{ "_id" : ObjectId("4b9e4a1fc583fa1c76198319"), "x" : [ 1, 2, 3, 2 ] }
> t.update({x: 2}, {$inc: {"x.$": 1}}, false, true);
> t.find();
{ "_id" : ObjectId("4b9e4a1fc583fa1c76198319"), "x" : [ 1, 3, 3, 2 ] }
//显然只是将第一个2增加了1
```