【问题标题】:laravel mongodb push element to existing array in document_laravel mongodb 将元素推送到 document_ 中的现有数组
【发布时间】:2014-03-18 21:57:45
【问题描述】:

在我的 mongodb 集合中,我想将一些元素推送到现有数组。我使用jenssegers/Laravel-MongoDB - Eloquent model and Query builder 来处理lavavel 和mongodb。

如何在 jenssegers/Laravel-MongoDB 中使用 $push 运算符?

应更新的 MongoDB 条目(RockMongo 表示):

{
   "_id": ObjectId("5328bc2627784fdb1a6cd398"),
   "comments": {
     "0": {
       "id": 3,
       "score": 8
    }
  },
   "created_at": ISODate("2014-03-18T21:35:34.0Z"),
   "file": {
     "file_id": NumberLong(1175),
     "timestamp": NumberLong(1395178534)
  }
}

关于 rockmongo 和 mongo shell 中数组表示的提示

RockMongomongo shell 数组表示的文档有点不同。看看comments-array。上面的 RockMongo 表示在 mongo shell 中显示为:

{ 
    "_id" : ObjectId("5328c33a27784f3b096cd39b"), 
    "comments" : [  
     {  
        "id" : 3,  
        "score" : 8 
     } 
    ], 
    "created_at" : ISODate("2014-03-18T22:05:46Z"), 
    "file" : { 
        "file_id" : NumberLong(1176), 
        "timestamp" : NumberLong(1395180346) 
    } 
}

正如文档所述,$push 操作员将元素推送到数组。这在 mongo-shell 中运行良好:

蒙古壳

db.Images.update({'file.file_id': 1175}, 
   { $push: { comments: { id: 3, score: 8} } 
})

但在查询构建器中,我很难合并 $push 运算符。我得到错误:

localhost:27017: Modified field name may not start with $

我没有找到任何说明如何操作的文档或示例。

我的 jenssegers/Laravel-MongoDB 代码,返回错误

// $file_id = 1175
public static function addComment( $file_id ) {  
    $image = Images::where( 'file.file_id', '=', floatval( $file_id ) )
    ->update( array('$push' => array( 'comments' => array( 'id' => 4, 'score' => 9 ) ) ) );
    return $image; 
} 

【问题讨论】:

    标签: php arrays mongodb laravel push


    【解决方案1】:

    假设一切正常,因为它在 shell 中工作,然后使用提供的方法来 push

    Images::where('file.file_id', '=', floatval( $file_id ))
       ->push('comments', array( 'id' => 4, 'score' => 9 ));
    

    【讨论】:

    • 在 mongo shell 中它可以工作......所以它应该是一个有效的数组。我知道是因为之前我遇到了它不是数组的问题,然后 mongo 向Cannot apply $push/$pushAll modifier to non-array 抱怨。无论如何都会测试你的建议。
    • @jerik 明白了。有一个特定的方法。 update 自己只做基本的操作
    • 完美运行!谢谢。还发现RockMongo 输出是错误的。您对结构的评论正确,因为相同的数组条目在 mongo shell 中显示为"comments" : [ { "id" : 3, "score" : 8 } ],在rockmongo 中显示为"comments": { "0": { "id": 3, "score": 8 } }。我使用rockmongo的表示来发帖。
    猜你喜欢
    • 2013-09-27
    • 1970-01-01
    • 1970-01-01
    • 2017-03-16
    • 2018-04-11
    • 1970-01-01
    • 2021-08-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多