【问题标题】:update value use $each in mongo更新值在 mongo 中使用 $each
【发布时间】:2014-04-27 08:30:56
【问题描述】:

我需要将所有看到的值 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,它根本不起作用

【问题讨论】:

  • 哪个问题?你为什么一开始就期望它起作用?您可以在此处参考您尝试使用的功能的手册吗?
  • $this->update(array('member_id'=>"53068" , "notifications.seen"=> "0"), array('$set' => array('notification_count' =>0 ,'notifications.$.seen' => "1"));

标签: php mongodb mongodb-php


【解决方案1】:

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

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

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

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

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

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)一起使用,这些运算符在这里不适用,因为它们是关于创建新元素的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-09
    • 1970-01-01
    • 2016-10-21
    • 2021-07-11
    • 2015-12-09
    相关资源
    最近更新 更多