MongoDB Basic Usage Summary (MongoDB 基本使用总结)

Comparison of DB structures

RDBMSMongoDB
DatabaseDatabase
TableCollection
RowDocument

Primary Key of a collection: _id Field

Create Database and Collection

There is no need to explicitly create database. Database can be automatically created once you add a collection (i.e. table) to it, and db is a shell variable representing the current database.

> show databases
> use databasename
switched to db databasename
> db
databasename
> show databases
> use databasename
switched to db databasename
> db.createCollection('table')
{ "ok" : 1 }
> show databases;
databasename  0.000GB
SyntaxExplanation
use databasenameSwitch to database ‘databasename’
dbShow current database
show databasesList all databases
db.getCollectionNames()List all collections in current db
show tablesList all collections in current db
show collectionsList all collections in current db
db.createCollection(‘table’)Create collection ‘table’ in current database

Drop Database and Collection

> db.table.drop()
true
> show tables
> db.dropDatabase()
{ "dropped" : "databasename", "ok" : 1 }
> show databases
SyntaxExplanation
db.table.drop()Drop collection ‘table’
db.dropDatabase()Drop current database

Insert Document

SyntaxExample
db.table.insert()db.person.insert({"_id":1, "name":"john smith", "address": {"street": "123 maple", "city": "LA", "zip": 91989}})
db.table.insert({"_id": ObjectId(), …})db.person.insert({"_id": ObjectId(), "name": "john smith"})
db.table.insertMany([{…}, {…}])db.person.insertMany([{"name": "kevin small", "age": 35, "scores":[5, 6, 3]}, {"name": "mary lou", "scores":[5,8,2]}])

Note:

  1. Attributes with single quotes ’ ’ or omitted quotes are acceptable.
  2. Duplicate key of “_id” is not acceptable.
  3. ObjectId() is automatically used when you insert doncument without specifying “_id”.
  4. ObjectId() is created with a 12-byte hexademical value, with 4 bytes of seconds since 1970/1/1, 3 bytes of machine identifier, 2 bytes of process id, 3 bytes of counter starting with a random value.
    E.g. 58250aec7c61126eba98db48
  5. db.table.insert([…]) can also take multiple docs.

Remove Document

SyntaxExampleExplanation
db.table.remove({})Remove all docs from the collection
db.person.remove({"age":{$gt:30}})Remove all docs whose “age” is over 30

Basic Query

SyntaxExampleExplanation
db.table.find()db.person.find()Return all docs in “person” collection
db.table.find({…})db.person.find({"info.name":"kevin small"})Return all docs with the specified “name” in “info” attribute (Embedded Document)
db.table.find().pretty()db.person.find().pretty()Pretty print

Note: Quotes in embedded doc are required.

Query Operator

Comparison OperatorExplanationExample
$lt, $gt, $lte, $gteless than, greater than, less than or equal, greater than equaldb.person.find({"age": {$gt:25, $lt:30}})
$eq, $ne, $in, $allValues of comparison operators are in arraydb.person.find({age:{$in:[25,35]}})

Note:

  1. Values of comparison operators are in array.
  2. The second example means finding people whose ages are either 25 or 35.
  3. db.person.find({"scores":{$gt: 20}})The “scores” field is an array and at least one value of the array should satisfy the specified condition (i.e., > 20)
Logical OperatorExplanationExample
$or, $andValues of $or, $and are in arraydb.person.find({$or:[{"name":"kevin small"}, {"age":{$gt: 25}}]}),
db.person.find({$and: [{"name":/kevin/i}, {"age":25}]}) equivalent to db.person.find({"name":"kevin small", "age": {$gt: 25}})
$not$not requires either a regex /…/ or a doc {…}db.person.find({name: {$not: {$eq: "john"}}})

Note:

  1. ERROR:
    – db.person.find({$not: {“name”: “david”}})
    – $not cannot be a top‐level operator.
  2. db.person.find({scores: {$all: [2, 5]}}) equivalent to db.person.find({$and: [{scores: 2}, {scores: 3}]})

Query with matching Pattern

SyntaxExplanationExample
db.table.find({ … : /…/ })Return all docs with the attribute matching the pattern in /…/db.person.find({"name":/Kevin/})
db.table.find({ … : /…/i })‘i’ means case insensitivedb.person.find({"name":/Kevin/i})
db.table.find({ … : {$regex : /… /, $options: ‘i’ }})Equivalent to db.table.find({ … : /…/i })db.person.find({"name":{$regex: /Kevin/, $options:'i'}})
db.table.find({ … : {$not: /…/ }})Return all docs without pattern in /…/ in the attributedb.person.find({"name": {$not: /john/i}})

Note: The last one also matches the docs without attribute “name”.

Condition on the same element of array

SyntaxExampleExplanation
db.table.find({ … : {$elemMatch: {…}}})db.person.find({"scores": {$elemMatch: {"midterm": "B", "score": {$gt: 90}}}})Return docs with “scores” satifying “midterm” is “B” and “score” is greater than 90 at the same time.

Sort, Skip, Limit

SyntaxExampleExplanation
db.table.find()sort({ … : 1})db.person.find().sort({"age" : -1})Retrurn all docs with sorting by age descending (1 for ascending; -1 for descending)
db.table.find().limit(…)db.person.find().limit(10)Return the first 10 docs
db.table.find().skip(…).limit(…)db.person.find().skip(2).limit(10)Return the first 10 docs with skipping the first 2

Projection

SyntaxExampleExplanation
db.table.find({… : 1})db.person.find({"age" : {$ne : 25}}, {"_id": 0, "name":1, "age":1})Return only “name” and “age” that “age” is not 25

Note:

  1. "_id" will also be shown if it is not specified with 0.
  2. Only "_id " can be assigned with 0; this is wrong: db.person.find({"age":{$ne:25}}, {"name":1, "age":0}).

Distinct, Count

SyntaxExampleExplanation
db.table.distinct()db.person.distince("age", {"age":{$gt:20}})Return all docs with distinct “age” with “age” over 20
db.table.distinct(…).lengthdb.person.distinct("age").lengthReturn the number of the query result

Note: Wrong Syntax: db.table.find(…).distinct(…)

SyntaxExampleExplanation
db.table.count()db.person.count({"age" : {$gt:25}})Return the number of the docs satisfying “age” is over 25
db.table.find(…).count()db.person.find({"age":{$gt:25}}).count()The same as above

Note: Watch out for null values when using comparison oprators.

Update (Upsert)

SyntaxExampleExplanation
db.table.update({…}, {…}, …)db.person.update({"age" : {$gt:25}}, {$set:{"status":"C", "gender":"M"}}, {multi:true})Update all docs setting “status” to “C” whose “age” is over 25

Note:

  1. If there is no attribute “status”, it will be an insert.
  2. If don’t use $set, it will be an overwriting.
  3. If there is no {multi:true}, it will only update one document.
  4. db.table.updateMany(...) is equivalent to db.table.update( ... , {multi:true}).
  5. db.person.update({}, {$set: {"status":"C"}}) adds “status” attribute to all docs.
SyntaxExampleExplanation
db.table.update( … , {upsert:true})db.person.update({"age":25}, {$set:{"name":"jonny"}}, {upsert:true})Insert if attribute “name” not exists; if no doc with “age”=25, a new doc will be inserted with ObjectId()
db.person.update({_id:2}, {$set:{"name":"jonny"}}, {upsert:true})If no doc with “_id”=2, a new doc with “_id”=2 will be inserted
SyntaxExampleExplanation
db.table.update( … , {$unset: { … : … }}, {multi:true})db.person.update({}, {$unset:{"status":"C"}})Remove all “status” that is “C” in all docs

Aggregation

Sample Collection for Aggregation:

> db.product.insertMany([{category:"cell",store:1,qty: 10}, {category:"cell",store:2,qty: 20}, {category:"laptop",store:1, qty: 10}, {category:"laptop",store:2, qty: 30}, {category:"laptop",store:2, qty: 40}])
FunctionExampleReturn
sumdb.product.aggregate({$group:{"_id":"$category", "total":{$sum:"$qty"}}}){ “_id” : “laptop”, “total” : 80 }
{ “_id” : “cell”, “total” : 30 }
sum on multiple fieldsdb.product.aggregate({$group:{"_id":{"cat":"$category", "st":"$store"}, "total":{$sum:"$qty"}}}){ “_id” : { “cat” : “laptop”, “st” : 1 }, “total” : 10 }
{ “_id” : { “cat” : “laptop”, “st” : 2 }, “total” : 70 }
{ “_id” : { “cat” : “cell”, “st” : 2 }, “total” : 20 }
{ “_id” : { “cat” : “cell”, “st” : 1 }, “total” : 10 }
countdb.product.aggregate({$group:{"_id":"$category", "total":{$sum:1}}}){ “_id” : “laptop”, “total” : 3 }
{ “_id” : “cell”, “total” : 2 }
sum & countdb.product.aggregate({$group:{"_id":"$category", "sum":{$sum:"$qty"}, "cnt":{$sum:1}}}){ “_id” : “laptop”, “sum” : 80, “cnt” : 3 }
{ “_id” : “cell”, “sum” : 30, “cnt” : 2 }
average$avg
min$min
max$max

Aggregation Pipeline:

ExampleReturnPipeline
db.product.aggregate({$match: {"store": 2}}, {$group: {"_id": "$category", "total": {$sum: "$qty"}}}, {$match: {"total": {$gt: 10}}}, {$limit: 2}, {$sort: {"total": 1}}){ “_id” : “cell”, “total” : 20 }
{ “_id” : “laptop”, “total” : 70 }
$match ‐> $group ‐> $match ‐> $limit ‐> $sort

Conditional Aggregation

SyntaxExampleReturn
db.table({$group:{ ... }}, {$match:{ ... }})db.product.aggregate({$group:{"_id":"$category", "total":{$sum:"$qty"}}}, {$match:{"total":{$gt:50}}}){ “_id” : “laptop”, “total” : 80 }

Projection in Aggregation

ExampleReturnExplanation
db.product.aggregate({$group:{"_id":null, "max":{$max:"$qty"}}}){ “_id” : null, “max” : 45 }Getting global max
db.product.aggregate({$group:{"_id": null, "max":{$max: "$qty"}}}, {$project: {"_id": 0}}){ “max” : 45 }Remove “_id” from result

Index

SyntaxExampleExplanation
db.table.getIndexes()db.users.getIndexes()Retrieve available indexes on users
db.table.createIndex({ … :1})db.users.createIndes({"score":1})Create an index on “score”, with indx entries sorted by “score”, ascending
db.table.createIndex({ … :1}, {unique:true})db.users.createIndex({"ssn":1}, {unique:true})Create a unique index of “ssn”, ascending
db.table.dropIndex( … )db.users.dropIndex("ssn")Drop the index of “ssn”

Note: Unique field can take null values.
Index is useful in searching and sorting.在这里插入图片描述

Query Plan

ExampleExplanation
db.users.explain().find({"score": {$gt: 30}})Retrieve the query plan of the query in MongoDB

Sharding in MongoDB

  • Distribute documents/records in a large collection/table over multiple machines
  • User can specify a sharding key – i.e., a field in a document
  • Support sharding by key range or hashing

Writing JavaScript

Mongo shell supports Javascripting.
E.g.

> var cursor = db.users.find();
  while ( cursor.hasNext() ) { 
		printjson( cursor.next() ); 
		}
> db.users.find().forEach( function (user) {printjson (user);} );

Other Useful Methods

• db.person.findOne()
– Find a single document
• db.person.deleteOne()
– Remove a single document
• db.person.explain().find({age: {$gt: 20}})
– Explain query execution plan

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值