MongoDBのクエリの備忘録 (Element)
準備
使用するMongoDBはこちらと同じ。
MongoDB Shellで接続して、マニュアルと同じテストデータを挿入する。
test> db.inventory.insertMany([ ... { item: "journal", qty: 25, tags: ["blank", "red"], dim_cm: [ 14, 21 ] }, ... { item: "notebook", qty: 50, tags: ["red", "blank"], dim_cm: [ 14, 21 ] }, ... { item: "paper", qty: 100, tags: ["red", "blank", "plain"], dim_cm: [ 14, 21 ] }, ... { item: "planner", qty: 75, tags: ["blank", "red"], dim_cm: [ 22.85, 30 ] }, ... { item: "postcard", qty: 45, tags: ["blue"], dim_cm: [ 10, 15.25 ] } ... ]); { acknowledged: true, insertedIds: { '0': ObjectId("63945c181ce8aac5f4f6e632"), '1': ObjectId("63945c181ce8aac5f4f6e633"), '2': ObjectId("63945c181ce8aac5f4f6e634"), '3': ObjectId("63945c181ce8aac5f4f6e635"), '4': ObjectId("63945c181ce8aac5f4f6e636") } }
テストデータを変更して、"notebook"のqty
fieldを削除、"paper"のqty
にnullを設定する。
test> db.inventory.updateOne({item: "notebook"}, {$unset: {qty: ""}}) { acknowledged: true, insertedId: null, matchedCount: 1, modifiedCount: 1, upsertedCount: 0 } test> db.inventory.updateOne({item: "paper"}, {$set: {qty: undefined}}) { acknowledged: true, insertedId: null, matchedCount: 1, modifiedCount: 1, upsertedCount: 0 }
Element Query Operators
exists
qty
fieldがあるdocumentを取得
(valueがnullのdocumentも含む)
test> db.inventory.find({qty: {$exists: true}}) [ { _id: ObjectId("63945c181ce8aac5f4f6e632"), item: 'journal', qty: 25, tags: [ 'blank', 'red' ], dim_cm: [ 14, 21 ] }, { _id: ObjectId("63945c181ce8aac5f4f6e634"), item: 'paper', qty: null, tags: [ 'red', 'blank', 'plain' ], dim_cm: [ 14, 21 ] }, { _id: ObjectId("63945c181ce8aac5f4f6e635"), item: 'planner', qty: 75, tags: [ 'blank', 'red' ], dim_cm: [ 22.85, 30 ] }, { _id: ObjectId("63945c181ce8aac5f4f6e636"), item: 'postcard', qty: 45, tags: [ 'blue' ], dim_cm: [ 10, 15.25 ] } ]
qty
fieldがないdocumentを取得
test> db.inventory.find({qty: {$exists: false}}) [ { _id: ObjectId("63945c181ce8aac5f4f6e633"), item: 'notebook', tags: [ 'red', 'blank' ], dim_cm: [ 14, 21 ] } ]
type
qty
のvalueがnumberのdocumentを取得
test> db.inventory.find({qty: {$type: "number"}}) [ { _id: ObjectId("63945c181ce8aac5f4f6e632"), item: 'journal', qty: 25, tags: [ 'blank', 'red' ], dim_cm: [ 14, 21 ] }, { _id: ObjectId("63945c181ce8aac5f4f6e635"), item: 'planner', qty: 75, tags: [ 'blank', 'red' ], dim_cm: [ 22.85, 30 ] }, { _id: ObjectId("63945c181ce8aac5f4f6e636"), item: 'postcard', qty: 45, tags: [ 'blue' ], dim_cm: [ 10, 15.25 ] } ]
qty
のvalueがnullのdocumentを取得
test> db.inventory.find({qty: {$type: "null"}}) [ { _id: ObjectId("63945c181ce8aac5f4f6e634"), item: 'paper', qty: null, tags: [ 'red', 'blank', 'plain' ], dim_cm: [ 14, 21 ] } ]