更新值在mongo中使用$ each

时间:2014-04-27 08:30:56

标签: php mongodb mongodb-php

我需要将所有看到的值0更新为1 使用mongo和php作为数组

enter code herearray (
  '_id' => new MongoId("5357c023dd34bcc9298b456e"),
  '_type' => 
  array (
    '0' => 'Altibbi_Mongo_MemberNotification',
  ),
  'member_id' => '53068',
  'notification_count' => new MongoInt32(30),
  'notifications' => 
  array (
    '0' => 
    array (
      'actor_id' => '0',
      'notification_type' => 'badge_top',
      'date_added' => '2014-04-23 16:29:07',
      'seen' => '0',
    ),
    '1' => 
    array (
      'actor_id' => '0',
      'notification_type' => 'badge_country',
      'date_added' => '2014-04-24 08:32:55',
      'seen' => '1',
    )
  ),
)

我需要任何帮助来解决问题我使用它只更新单个第一个值 我使用$ each,它根本不起作用

1 个答案:

答案 0 :(得分:0)

您尝试使用的positional $运算符更新从更新语句的查询端匹配的第一个元素。这是目前的设计和文档中提到的。

要更新多个职位,您必须:

  1. 针对文档发出多个更新语句,直到修改后的计数返回为0.

  2. 检索文档并修改数组的每个元素以设置新值。

  3. 第二种方法的典型编码示例如下:

    var doc = db.collection.findOne({ "member_id": "53068" })
    
    for ( var x = 0; x < doc.notifications.length; x++ ) {
        if ( doc.notifications[x].seen == 0 ) {
            var obj = {};
            obj["notifications." + x] = 1;
            db.collection.update(
                { "member_id": "53068" },
                { "$set": obj }
            );
        }
    }
    

    您引用的$each运算符用于指定多个数组元素,以便与其他运算符(例如$push$addToSet一起使用,这些运算符在此处不适用,因为它们与创建新元素有关。