更新()的查找部分中的mongodb位置运算符

时间:2014-05-09 22:43:34

标签: mongodb mongodb-query positional-operator

我试图更新我的mongodb集合中的某个字段'用户'

文件示例:

{
  _id: ObjectId("536d4d3307221f847fbbea49"),
  groups: [
    {
      match_id: "dc3acf1b",
      groupName: "World Cup, Group A",
      score:[0,1]
    },
    {
      match_id: "d4f14940",
      groupName: "World Cup, Group A",
      score:[2,1]
    }],
  name:"Foo Bar",
  points:10
}

我试图仅更新具有特定分数的分数字段。

这是我想要的(位置操作员):

db.users.update({'groups.match_id':i_match , 'groups.score':i_score},
                {$inc:{points:1}});

现在我认为这会找到同时具有这两个字段的用户,但我想查看具有查询第一部分的相同组对象。

如:

 db.users.update({'groups.match_id':d4f14940 , 'groups.score':[2,1]},
                    {$inc:{points:1}});

应该给用户+1分

可是:

 db.users.update({'groups.match_id':dc3acf1b , 'groups.score':[2,1]},
                        {$inc:{points:1}});

不应该

你得到我的漂移:)。

现在我从positional operator知道我应该使用' $'签名,但我认为只能在update()的第二个参数中使用 - 更新部分......而不是查找部分

注意 - 以这种方式(数组)对分数进行实际比较可能无效..但这不是问题

1 个答案:

答案 0 :(得分:1)

你想要的是$elemMatch运营商。这允许您选择需要多个字段来匹配条件的数组元素:

db.users.update(
    { "groups": { 
        "$elemMatch": {
          "match_id": "d4f14940",
          "score": [2,1]
        }      
    }},
    { "$inc": { "points": 1 } }
)

因此,您可以匹配文档,因为“groups”数组包含的match_idscore符合您提供的条件。如果您在不改变分数的情况下更改match_id,则文档不匹配,并且不会对您的points值进行增量。

因此,在这种情况下,这与位置$运算符无关,因为您没有在匹配位置更新和数组,这就是它的用途。