ほげほげ

プログラミング、英会話、ヨガ、料理などの備忘録など。

mongo ドキュメント内の配列に要素を追加する

ドキュメント内の配列に要素を追加する方法。
$pushを使用する。
ブログ記事のドキュメントを例に簡単に使用方法をメモ。
参考$push — MongoDB Manual 2.6.0

ダミーデータの準備
db.articles.insert({'author':'hoge','body':'bodybodybody',
 'comments':['c1','c2']}) ;
$pushの使い方
// コメントを追加する
db.articles.update({author:"hoge"},{$push:{comments:'c3'}}) ;

// コメントを複数追加する
db.articles.update({author:"hoge"},{$push:{comments:{$each:['c4','c5']}}}) ;

// 確認
db.articles.find({author:"hoge"}) ;