1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

MongoDB 基礎

1
Posted at

Collection

RDBのテーブルに該当するようなもの

Document

RDBのレコードのようなもの
JavaScriptのオブジェクトの形式でデータを入れていく

例)
{
name: "taguchi",
score: 30
}

キーのことをフィールドと読んだりする

mongoDBはスキーマレスの為、Documentに入るデータの構造を予め決めておく必要がない

コマンド

show dbs;

データベースの表示

show collections;

コレクションの表示

use test;

testデータベースへの切り替え、存在しない場合、testデータベースの作成
test箇所は任意で指定可能

※データベースの中にコレクションとドキュメントが作られていない場合、存在しないことになっている。

db.createCollection("testCollection");

コレクションの作成

db.stats();

現在のデータベースに関する情報を表示

db.dropDatabase();

現在のデータベースの削除

db.dataBaseName.renameCollection("changeName");

コレクション名の変更

db.colelctionName.drop();

コレクションの削除

db.documentName.insert({ name: "k47", age: 26 });

ドキュメント挿入
コレクションは、ドキュメントを作成すると自動的に作成される

db.collectionName.find();

指定したコレクション内のドキュメントを全て表示

※"_id"はmongoDBが自動で作成するもの(データをユニーク(一意)にする為のもの)

&条件の場合は、引数にカンマ区切りで条件を追加していく

db.collectionName.find({$or: [{条件1}, {条件2}...]});

or条件の場合

db.collectionName.find({feeldName: {$in: [値1, 値2]}});

フィールド内が同じ中でのor条件の場合

db.collectionName.remove({});

指定したコレクション内のドキュメントを全て削除

db.collectionName.remove({抽出条件});

抽出条件に合致したドキュメントの削除

$gte

grater than or equal

{$gte: 10}
10以上

$gt

grater than

{$gt: 10}
10より大きい

$lte

less than or equal

{$lte: 10}
10以下

$lt

less than

{$lt: 10}
10より小さい

$eq

equal

$ne

not equal

db.collectionName.distinct( "feeldName" );

フィールドの値を出力

db.collectionName.find({ feeldName: { $exists: 真偽値});

指定したフィールドが存在するドキュメントを出力

db.collectionName.find({}, { feeldName1:真偽値, feeldName2:真偽値 });

指定したフィールドを出力する
※trueならtrueのみ、falseならfalseのみ。真偽値の混在は不可
("_id"に関しては、非表示(false)が可能)

db.collectionName.find({},{}).sort({feeldName: 1});

検索結果のソート
1 昇順
-1 降順

db.collectionName.find({},{}).limit(num);

検索結果の件数を引数の数だけ出力する

db.collectionName.findOne({},{});

該当する1件目だけを出力

db.collectionName.find().skip(num);

引数の数だけ出力を飛ばせる
numが3であれば、検索結果の4件目から出力される

db.collectionName.update({抽出条件},{feeldName:値});

抽出条件のdocumentを丸ごと上書き

db.collectionName.update({抽出条件},{#set: {feeldName: 値});

フィールドの値の更新

.update()は該当した最初の1件を更新する

db.collectionName.update({抽出条件},{更新する値},{multi:true})

該当する全件を更新する

db.collectionName.update({抽出条件},{更新する値},{upsert:true});

抽出条件に合致するドキュメントがなければ作成

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?