LoginSignup
13
14

More than 5 years have passed since last update.

よく忘れるMongoDBのコマンド、クエリー

Last updated at Posted at 2014-01-23

mongoexportで時間指定

ポイント
mongoexportで時間指定する場合、longで日時を指定しなければならない。※ISODateが使えない

書き方

  • 'field'が'2014-01-22T09:55:47.924Z'のドキュメントを検索。
クエリーの書き方
--query "{'field' : new Date(1390384547924)}" 
  • 'field'が'2014-01-22T09:55:47.924Z'以前のドキュメントを検索。
クエリーの書き方
--query "{'dateCreated' : {'$lt' : new Date(1390384547924)}}" 

使用例

example
mongoexport -h localhost --port 27017 --db dbname --collection collectionname  --query "{'dateCreated' : new Date(1390384547924)}" 

条件を指定して1件削除する。 (findAndModify)

ポイント
{remove: true}として、findAndModifyを使う。
クエリーに合致するドキュメントを一つ削除する。

書き方

db.Collection.findAndModify({query : {クエリー}, remove: true})
example
db.myCollection.findAndModify({query : {"name" : "myDocument"}, remove: true})

ドキュメントの一部だけ更新する

ポイント
update+$setを使う。

書き方

db.collection.update({クエリー},{$set:{設定内容}})
db.collection.findAndModify({クエリー},{$set:{設定内容}})

使用例

example
// 更新前ドキュメント確認
db.myCollection.find({"key" : "value1"}).pretty()
// 更新
db.myCollection.update({"key" : "value1"},{$set:{"field" : "value2"}})
// 更新後ドキュメント確認
db.myCollection.find({"key" : "value1"}).pretty()
example
// ドキュメント検索&更新
db.myCollection.findAndModify({"key" : "value1"},{$set:{"field" : "value2"}})
// 更新後ドキュメント確認
db.myCollection.find({"key" : "value1"}).pretty()
example
// { multi: true }をつけると、複数行まとめて更新される
db.myCollection.update({"key" : "value1"},{$set:{"field" : "value2"}}, {"multi":true}))

JSONによるクエリーで、IDを指定して検索する。

ポイント
ObjectId()が使えないケースは、$oidを使う。
使いどころは、クエリーをテキストで受け取って、検索を実行する場合など。
書き方

db.collection.find({"_id": {"$oid": ID文字列}}})

※db.collection.find({"_id": ObjectId(ID文字列)}})と同じになる

使用例

example
db.collection.find({"_id": {"$oid": "xxxxxxxxxxxxxxxxxxxxxx"}}})
13
14
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
13
14