● Mangodb commands
● Use library
● db.createCollection("books")
● db.posts.insertOne({
title: "the magic of thinking",
author: " David J Schwartz ",
likes: 100,
tags: ["moral", "life"]
})
● db.posts.insertMany([
{title: "the color of magic",
author: " Terry",
likes: 200,
tags: ["moral", "life"]
},
{
},
{
}
])
1)db.books.find()
2)db.books.findOne()
3)db.books.find( {title: "the magic of thinking"} )
4)db.books.find({}, {title: 1, likes: 1})
5)db.books.find().count()
6)db.books.find({author: David J Schwartz}).count()
8)db.posts.updateMany({}, { $inc: { likes: 1 } })
db.books.updateOne( { title: "the magic of thinking" }, { $set: { likes: 2 } } )
7)db.posts.updateOne(
{ title: "Post Title 5" },
{
$set:
{
title: "Post Title 5",
body: "Body of post.",
category: "Event",
likes: 5,
tags: ["news", "events"],
date: Date()
}
},
{ upsert: true }
)
Delete
1)deleteOne()
db.posts.deleteOne({ title: "magic of big thinking" })
2)db.posts.deleteMany({ category: "Technology" })
MongoDB Update Operators
Fields
The following operators can be used to update fields:
● $currentDate: Sets the field value to the current date
● $inc: Increments the field value
● $rename: Renames the field
● $set: Sets the value of a field
● $unset: Removes the field from the document
Array
The following operators assist with updating arrays.
● $addToSet: Adds distinct elements to an array
● $pop: Removes the first or last element of an array
● $pull: Removes all elements from an array that match the query
● $push: Adds an element to an array
db.books.updateOne({'title':'the color of magic'},{$set:{'title' :'updated'}})