— Technology — 1 min read
1show dbs
1db
1use acme
1db.dropDatabase()
1db.createCollection('posts')
1show collections
1db.posts.insert({2 title: 'Post One',3 body: 'Body of post one',4 category: 'News',5 tags: ['news', 'events'],6 user: {7 name: 'John Doe',8 status: 'author'9 },10 date: Date()11})
1db.posts.insertMany([2 {3 title: 'Post Two',4 body: 'Body of post two',5 category: 'Technology',6 date: Date()7 },8 {9 title: 'Post Three',10 body: 'Body of post three',11 category: 'News',12 date: Date()13 },14 {15 title: 'Post Four',16 body: 'Body of post three',17 category: 'Entertainment',18 date: Date()19 }20])
1db.posts.find()
1db.find().pretty()
1db.posts.find({ category: 'News' })
1# asc2db.posts.find().sort({ title: 1 }).pretty()3# desc4db.posts.find().sort({ title: -1 }).pretty()
1db.posts.find().count()2db.posts.find({ category: 'news' }).count()
1db.posts.find().limit(2).pretty()
1db.posts.find().limit(2).sort({ title: 1 }).pretty()
1db.posts.find().forEach(function(doc) {2 print("Blog Post: " + doc.title)3})
1db.posts.findOne({ category: 'News' })
1db.posts.find({ title: 'Post One' }, {2 title: 1,3 author: 14})
1db.posts.update({ title: 'Post Two' },2{3 title: 'Post Two',4 body: 'New body for post 2',5 date: Date()6},7{8 upsert: true9})
1db.posts.update({ title: 'Post Two' },2{3 $set: {4 body: 'Body for post 2',5 category: 'Technology'6 }7})
1db.posts.update({ title: 'Post Two' },2{3 $inc: {4 likes: 55 }6})
1db.posts.update({ title: 'Post Two' },2{3 $rename: {4 likes: 'views'5 }6})
1db.posts.remove({ title: 'Post Four' })
1db.posts.update({ title: 'Post One' },2{3 $set: {4 comments: [5 {6 body: 'Comment One',7 user: 'Mary Williams',8 date: Date()9 },10 {11 body: 'Comment Two',12 user: 'Harry White',13 date: Date()14 }15 ]16 }17})
1db.posts.find({2 comments: {3 $elemMatch: {4 user: 'Mary Williams'5 }6 }7 }8)
1db.posts.createIndex({ title: 'text' })
1db.posts.find({2 $text: {3 $search: "\"Post O\""4 }5})
1db.posts.find({ views: { $gt: 2 } })2db.posts.find({ views: { $gte: 7 } })3db.posts.find({ views: { $lt: 7 } })4db.posts.find({ views: { $lte: 7 } })