【问题标题】:mongodb positional operator in the find part of update()update() 的 find 部分中的 mongodb 位置运算符
【发布时间】:2014-06-27 19:26:28
【问题描述】:

我正在尝试更新我的 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() 的第二个参数中使用 - 更新部分..而不是查找部分

注意 - 以这种方式(数组)实际比较分数可能不起作用..但这不是这里的问题

【问题讨论】:

    标签: mongodb mongodb-query positional-operator


    【解决方案1】:

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

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

    这样您就可以匹配文档,因为“groups”数组包含的元素同时具有满足您提供的条件的match_idscore。如果您在不更改分数的情况下更改 match_id,则文档不匹配,并且不会对您的 points 值进行增量。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-06
      • 2015-01-25
      • 2021-09-18
      • 2017-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-10
      相关资源
      最近更新 更多