douting1871 2017-06-05 07:45
浏览 85
已采纳

laravel-mongodb与嵌套对象的增量

I have a post documents that schema looks like

    {
        "author": {
            "name": "John",
            "gender": 0
        },
        "stats": {
            "likes": 0
        },
        "content": "The new post",
        "updated_at": "2017-06-05 15:15:21",
        "created_at": "2017-06-04 18:10:30",
    }

How can I update the stats.likes field through jenssegers/laravel-mongodb

According to the GitHub page, There are a method increment() that can be used. So I was trying this way

Post::findOrFail( $request->id )->increment('stats.likes');

But got

ErrorException in HasAttributes.php line 906:
Undefined index: stats.likes

However, with the mongo shell, it can work at the code

db.posts.update( { '_id': ObjectId('5933dc7d4abcf141956a6250') }, { '$inc': { 'stats.likes': 1 } )  )

Is that an error caused by nested object?

According to the source code, I found

/**
 * @inheritdoc
 */
public function increment($column, $amount = 1, array $extra = [], array $options = [])
{
    $query = ['$inc' => [$column => $amount]];

    if (! empty($extra)) {
        $query['$set'] = $extra;
    }

    // Protect
    $this->where(function ($query) use ($column) {
        $query->where($column, 'exists', false);

        $query->orWhereNotNull($column);
    });

    return $this->performUpdate($query, $options);
}

If I'm not wrong, the field name stats.likes will pass to the shell directly at the 1st parameter of the method. Why it can just work with the command line?

  • MongoDB 3.4
  • jenssegers/laravel-mongodb 3.2
  • Laravel 5.4
  • 写回答

1条回答 默认 最新

  • dsajdgjadwqe3247382 2017-06-07 09:02
    关注

    Since I can update a nested object through the shell, I wrote a raw expression below alternatively:

    $result = Post::raw(function($collection) use ($request){
    
        return $collection->findOneAndUpdate([
            '_id' => new \MongoDB\BSON\ObjectID ($request->_id),
        ], [ '$inc' => [ 'stats.likes' => 1 ] ] );
    
    });
    

    Notice that you may have effect with db.articles.update(), but the Mongo\Collection doesn't have a method named update(), use findOneAndUpdate, or others instead. (UpdateMany, UpdateOne)

    And if the where condition contains _id, you have to wrap your id variable with \MongoDB\BSON\ObjectID object in the case of raw expression.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 为什么我写出来的绘图程序是这样的,有没有lao哥改一下
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥200 关于#c++#的问题,请各位专家解答!网站的邀请码
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥15 绘制多分类任务的roc曲线时只画出了一类的roc,其它的auc显示为nan
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号