Question

In my mongodb collection I want to push some elements to an existing array. I use jenssegers/Laravel-MongoDB - Eloquent model and Query builder to work with lavavel and mongodb.

How can I use the $push operator in jenssegers/Laravel-MongoDB?

MongoDB entry which shall be updated (RockMongo representation):

{
   "_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)
  }
}

Hint about array representation in rockmongo and mongo shell

RockMongo and mongo shell array representation of the documents are a little bit different. Have a look at the comments-array. The above RockMongo representation appears in the mongo shell as:

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

As the documentation states the $push operater to push elements to an array. This works fine in the mongo-shell:

Mongo shell

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

But in the query-builder I struggle to incorporate the $push operator. I get the error:

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

I did not find any documentation or example that showed me how to do it..

My jenssegers/Laravel-MongoDB code, that returns the error

// $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; 
} 
Was it helpful?

Solution

Assuming everything is okay as it works in the shell then use the provided method to push instead:

Images::where('file.file_id', '=', floatval( $file_id ))
   ->push('comments', array( 'id' => 4, 'score' => 9 ));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top