LoginSignup
0
0

More than 5 years have passed since last update.

MACにMongoDBをインストール&ちょっと使ってみる

Posted at

インストール

$ sudo brew update
$ sudo brew install mongodb

起動

$ brew services start mongodb

動作確認

$ mongo -version
MongoDB shell version: 3.2.8

MongoDBへの接続

$ mongo
MongoDB shell version: 3.2.8
connecting to: test

コレクション作成とデータ追加

> use sample-mongo
> db.test.insert({_id:1,title:"MongoDBタイトル1",price:100});
WriteResult({ "nInserted" : 1 })
> db.test.insert({_id:2,title:"MongoDBタイトル2",price:200});
WriteResult({ "nInserted" : 1 })

データ取得

# 全件取得
> db.test.find()
{ "_id" : 1, "title" : “MongoDBタイトル1", "price" : 100 }
{ "_id" : 2, "title" : "MongoDBタイトル2", "price" : 200 }
# 条件指定
> db.test.find({_id:{$eq:2}});
{ "_id" : 2, "title" : "MongoDBタイトル2", "price" : 200 }

データ更新

> db.test.update({ _id:2 }, { $set : { title: "MongoDB タイトル Updated" } });
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
# 確認
> db.test.find({_id:{$eq:2}});
{ "_id" : 2, "title" : "MongoDB タイトル Updated", "price" : 200 }

update field operator

updateの第3引数にtrueを渡すと、下記の場合にはinsert、そうでなければupdateという動作になります。
- コレクションが存在しない
- 該当するドキュメントがない

 上のupdateで指定している「$set」とは、「update field operator」と呼ばれるものです。
詳細はField Update Operatorsへ。

データ削除

> db.test.remove({ _id:1 })
WriteResult({ "nRemoved" : 1 })
# 確認
> db.test.find({_id:{$eq:1}});
>

コレクション削除

> db.test.drop()
true
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0