- vừa được xem lúc

[DATABASE - MONGO] Working with MongoDB Shell

0 0 8

Người đăng: Vivian

Theo Viblo Asia

I. Introduction

  • mongo shell is an interactive JS interface to MongoDB.
  • mongo shell uses commands to perform direct operations to the database such as query, update, etc...

II. Commands to work with mongo shell

1. Basic commands

  • Open Command Prompt > type mongo command to open mongo shell.
  • show dbs : shows all database you have.
  • use databaseName: switches to the database if it exists, else create new database.
  • db: shows the current database you are using.
  • show collections: shows all collections in the current database.
  • exit: exits the shell.

2. Adding new documents to a collection

  • db.collectionName.insertOne({bson}): inserts one document at a time
  • db.collectionName.insertMany([{bson}, {bson}]): insert many documents at a time
// opens userRelatedInfo database
use userRelatedInfo
// adds user named Vivian to the users collectoin 
db.users.insertOne( { name: "Vivian", sex: "Female" }
)

3. Finding documents

  • db.collectionName.findOne({}): returns the first document in the collection.
  • db.collectionName.findOne({field: "value", field1: "value"}): returns the first document matching the condition.
  • db.collectionName.find()/find({}): lists the first 20 documents > it for more documents.
  • db.collectionName.find({field: "value", field1: "value"}): returns all documents maching the condition.
  • db.collectionName.find({condtion},{fieldName: 1, fieldName: 1}): returns documents maching the condition, arg2 to specified which field can be printed to the shell.
{ "_id" : ObjectId("64e13bdf6847f9e80d312d29"), "name" : "Vivian", "sex" : "Female", "rank":10 } // finds user with name Vivian and only display her rank
db.users.find({"name": "Vivian"}, {rank: 1, _id: 0})

4. Sorting and limiting data

  • db.collectionName.find(condition).count(): returns the number of matching documents.
  • db.collectionName.find(condition).limit(number): prints only a number of document based on number specified.
  • db.collectionName.find(condition).sort({field: number}): sorts the matching documents based on number specified, if number > 1, field is sorted in ascending order. if number < 1, it sorts in decending order.

5. Complex query with operators

  • $gt, $lt, $lte, $gte
// finds all users whoes age is greater than 18
db.users.find( { "age": { $gt: 18 } } )
  • $or
// matches users whose age is 18 or 19
db.users.find( {$or: [{age: 18}, {age: 19}] })
  • $in: matches in range
  • $nin: not matches in range
// matches users whose age is between 18-20
dbdb.users.find({ "age": {$in: [18,19,20]} })
// matches users whose age is less than 18 and greater than 20
dbdb.users.find({ "age": {$nin: [18,19,20]} })
  • $inc: increases value
  • $pull: takes out a value of an array
  • $push: adds a new value to an array
  • $each: loops

6. Deleting documents

  • db.collectionName.deleteOne({field: value}): deletes the first document matching the condition.
  • db.collectionName.deleteMany({condition}): deletes all documents matching the condition.

7. Updating documents

  • db.collectionName.updateOne({name: "Vivian"}, {$set: {name: "Vivian Vu", rank: 8}}): finds the first document matching the condition then updates its value based on arg2.
  • db.collectionName.updateMany({condition},{$set: {field1: newVal, field2, newVal}}): finds all matching documents then updates their values based on arg2.

III. Nested documents

1. Example

{ name: "Wimpy Kid", author: { lastname: "Kinney", firstname: "Jeff" , } genre: ["Comedy", "Fiction"], reader: [ {name: "Vivian", age: 18}, {name: "Irene", age: 20} ]
} 

1. Querying arrays

  • { field : value } : value is the exact array to match, including the order of the elements.
  • { array field: { operator1: value1, ... } }
// dress collection colors: ['red', 'black'] // height collection heights: [10, 15.25] // match an array with exact order
db.dress.find({colors:['red','black']}) // match an array without exact order 
db.dress.find({colors: {$all: ['red','black'] }}) // query an array for an element
db.dress.find({colors: 'red' })
db.heights.find({ heights: {$gt: 10, $lt:12}}) // query an array by array length
db.heights.find({ heights: {$size: 3}})

Bình luận

Bài viết tương tự

- vừa được xem lúc

TÌM HIỂU VỀ MONGODB

. 1. Định nghĩa về MongoDB. . MongoDB là một cơ sở dữ liệu mã nguồn mở và là cơ sở dữ liệu NoSQL(*) hàng đầu, được hàng triệu người sử dụng.

0 0 31

- vừa được xem lúc

Mongo DB cho người mới bắt đầu !

Lời nói đầu. Gần đây, mình mới bắt đầu nghiên cứu và sử dụng mongo db nên có chút kiến thức cơ bản về Mongo muốn share và note ra đây coi như để nhở (Biết đâu sẽ có ích cho ai đó).

0 0 23

- vừa được xem lúc

Áp dụng kiến trúc 3 Layer Architecture vào project NodeJS

The problem encountered. Các framework nodejs phổ biết như Express cho phép chúng ta dễ dàng tạo ra Resful API xử lí các request từ phía client một cách nhanh chóng và linh hoạt.

0 0 64

- vừa được xem lúc

Mongo DB cho người mới bắt đầu ! (P2)

Lời nói đầu. Gần đây, mình mới bắt đầu nghiên cứu và sử dụng mongo db nên có chút kiến thức cơ bản về Mongo muốn share và note ra đây coi như để nhở (Biết đâu sẽ có ích cho ai đó).

0 0 169

- vừa được xem lúc

Xây dựng CRUD RESTful API sử dụng Node, Express, MongoDB.

Introduction. Trong phạm vi bài viết này chúng ta sẽ cùng tìm hiểu về cách tạo restful api với Node, Express và MongoDB. . Xử lý các hoạt động crud.

0 0 213

- vừa được xem lúc

MongoDB là gì? Cơ sở dữ liệu phi quan hệ

Bài viết này mình sẽ giúp các bạn có cái nhìn tổng quan về MongoDB. Chúng ta không lạ gì với cơ sở dữ liệu quan hệ, còn với cơ sở dữ liệu phi quan hệ thì sao? MEAN stack (MongoDB, Express, AngularJS,

0 0 38