mongodb shell operation command

Keywords: less

1. Insert operation details
Insert a document
db.collection.insertOne()

db.inventory.insertOne(
   { item: "canvas", qty: 100, tags: ["cotton"], size: { h: 28, w: 35.5, uom: "cm" } }
)

Insert multiple documents
db.collection.insertMany()

db.inventory.insertMany([
   { item: "journal", qty: 25, tags: ["blank", "red"], size: { h: 14, w: 21, uom: "cm" } },
   { item: "mat", qty: 85, tags: ["gray"], size: { h: 27.9, w: 35.5, uom: "cm" } },
   { item: "mousepad", qty: 25, tags: ["gel", "blue"], size: { h: 19, w: 22.85, uom: "cm" } }
])

db.collection.insert()

db.collection.insert(
   <document or array of documents>,
   {
     writeConcern: <document>,
     ordered: <boolean>
   }
)

2. Query operation details
Query all

db.collection.find()

Equivalent to: select * from table [name]

Query by criteria

db.collection.find({ke:value})

Equivalent to select * from table "name where name =?

Use query operators to specify conditions

db.inventory.find( { status: { $in: [ "A", "D" ] } } )
//Amount to
SELECT * FROM inventory WHERE status in ("A", "D")

Specify AND condition query
less than ($lt)

db.inventory.find( { status: "A", qty: { $lt: 30 } } )
//Amount to
SELECT * FROM inventory WHERE status = "A" AND qty < 30

Specify OR condition

db.inventory.find( { $or: [ { status: "A" }, { qty: { $lt: 30 } } ] } )
//Amount to
SELECT * FROM inventory WHERE status = "A" OR qty < 30

Specify AND and OR conditions

db.inventory.find( {
     status: "A",
     $or: [ { qty: { $lt: 30 } }, { item: /^p/ } ]
} )
//Amount to
SELECT  *  FROM  inventory  WHERE  status  =  "A"  AND  ( qty  <  30  OR  item  LIKE  "p%" )

3. Update operation details
Update single document db.collection.updateOne()

db.inventory.updateOne(
   { item: "paper" },
   {
     $set: { "size.uom": "cm", status: "P" },
     $currentDate: { lastModified: true }
   }
)

Update multiple documents db.collection.updateMany()

db.inventory.updateMany(
   { "qty": { $lt: 50 } },
   {
     $set: { "size.uom": "in", status: "P" },
     $currentDate: { lastModified: true }
   }
)

Replace document db.collection.replaceOne()

db.inventory.replaceOne(
   { item: "paper" },
   { item: "paper", instock: [ { warehouse: "A", qty: 60 }, { warehouse: "B", qty: 40 } ] }
)

4. Delete operation details
Delete all documents db.collection.deleteMany()

db.inventory.deleteMany({})

Delete documents matching criteria

db.inventory.deleteMany({ status : "A" })

Delete a document that matches the criteria

db.inventory.deleteOne( { status: "D" } )

Posted by fiona on Wed, 30 Oct 2019 07:57:39 -0700