MongoDB学习笔记

本文是基于MongoDB v3.4和Shell v2.7的MongoDB学习笔记,包括MongoDB常用操作、MongoDB CRUD操作和MongoDB安装及启动三部分内容。

MongoDB常用操作

Admin添加User
> use admin
> show users    
> db.createUser({user:"abc",pwd:"abc",roles:["readWrite"]}) 
> db.createUser(  
  {  
    user: "dbadmin",  
    pwd: "dbadmin",  
    roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]  
  } 
> db.dropUser("dbadmin")
DataBase操作
> use mytest
> db.stats()
> db.version() 
> db.getMongo()          //查看当前db链接机器地址
> db.dropDatabase()
> db.auth("abc","abc")   //数据库认证+安全模式
Collection操作
> use mytest
> show collections
> db.getCollectionNames()
> db.collection.insert({username:"a"})
> db.collection.find().pretty();
> db.collection.find({username: "a"}).pretty()
> db.collection.find({$and: [{id: ObjectId("55e44fdf22")}, {username: "s"}]})
> db.collection.update({username: "a"},{$set: {country: "B"}})  #修改
> db.collection.update({username: "a"},  {country: "B"})  #替换
> db.collection.update({username: "a"},{$unset: {country: "B"}})  #删除
> db.collection.update( {"favorites.movies": "C"},{$addToSet: {"favorites.movies": "M"}},false,true)  #(查询条件, $addToSet, 文档不存在是否插入, 是否多个更新)
> db.collection.remove({"favorite.cities": "C"})  #删除集合中的文档
> db.collection.drop()  #删除集合

MongoDB CRUD示例

Create Operations
# 将文档插入到集合
> db.collection.insertOne() 
> db.collection.insertMany() 
# 插入文档示例
# Insert a Single Document
> db.inventory.insertOne(
   { item: "canvas", qty: 100, tags: ["cotton"], size: { h: 28, w: 35.5, uom: "cm" } }
  )
# To retrieve the document that you just inserted
> db.inventory.find( { item: "canvas" } )

# Insert Multiple Documents
> 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" } }
  ])
# To retrieve the inserted documents
> db.inventory.find( {} )
Read Operations
# 从集合中检索文档
> db.collection.find()
# 查询文档示例
# To populate the inventory collection
> db.inventory.insertMany([
   { item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
   { item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "A" },
   { item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" },
   { item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" },
   { item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" }
  ]);
# 查询文件 
# SELECT * FROM inventory WHERE status = "D"
> db.inventory.find( { status: "D" } )

# SELECT * FROM inventory WHERE status in ("A", "D")
# use the $in operator rather than the $or operator when performing equality checks on the same field
> db.inventory.find( { status: { $in: [ "A", "D" ] } } )

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

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

# SELECT * FROM inventory WHERE status = "A" AND ( qty < 30 OR item LIKE "p%")
# selects all documents in the collection where the status equals "A" and either qty is less than ($lt) 30 or item starts with the character p
> db.inventory.find( {
     status: "A",
     $or: [ { qty: { $lt: 30 } }, { item: /^p/ } ]
  } )
# 查询嵌入/嵌套文档
# To populate the inventory collection
> db.inventory.insertMany( [
   { item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
   { item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "A" },
   { item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" },
   { item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" },
   { item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" }
  ]);

# Match an Embedded/Nested Document
# selects all documents where the field size equals the document { h: 14, w: 21, uom: "cm" }
> db.inventory.find( { size: { h: 14, w: 21, uom: "cm" } } )

# Query on Nested Field
# selects all documents where the field uom nested in the size field equals "in"
> db.inventory.find( { "size.uom": "in" } )
# query uses the less than operator ($lt) on the field h embedded in the size field
> db.inventory.find( { "size.h": { $lt: 15 } } )
# query selects all documents where the nested field h is less than 15, the nested field uom equals "in", and the status field equals "D"
> db.inventory.find( { "size.h": { $lt: 15 }, "size.uom": "in", status: "D" } )
# 查询数组
# To populate the inventory collection
> db.inventory.insertMany([
   { item: "journal", qty: 25, tags: ["blank", "red"], dim_cm: [ 14, 21 ] },
   { item: "notebook", qty: 50, tags: ["red", "blank"], dim_cm: [ 14, 21 ] },
   { item: "paper", qty: 100, tags: ["red", "blank", "plain"], dim_cm: [ 14, 21 ] },
   { item: "planner", qty: 75, tags: ["blank", "red"], dim_cm: [ 22.85, 30 ] },
   { item: "postcard", qty: 45, tags: ["blue"], dim_cm: [ 10, 15.25 ] }
  ]);

# Match an Array
# queries for all documents where the field tags value is an array with exactly two elements, "red" and "blank"
> db.inventory.find( { tags: ["red", "blank"] } )
# find an array that contains both the elements "red" and "blank", without regard to order or other elements in the array
> db.inventory.find( { tags: { $all: ["red", "blank"] } } )

# Query an Array for an Element
# queries for all documents where tags is an array that contains the string "red" as one of its elements
> db.inventory.find( { tags: "red" } )
#  queries for all documents where the array dim_cm contains at least one element whose value is greater than 25
> db.inventory.find( { dim_cm: { $gt: 25 } } )

# Query an Array with Compound Filter Conditions on the Array Elements
# queries for documents where the dim_cm array contains elements that in some combination satisfy the query conditions
> db.inventory.find( { dim_cm: { $gt: 15, $lt: 20 } } )

# Query for an Array Element that Meets Multiple Criteria
# queries for documents where the dim_cm array contains at least one element that is both greater than ($gt) 22 and less than ($lt) 30
> db.inventory.find( { dim_cm: { $elemMatch: { $gt: 22, $lt: 30 } } } )

# Query for an Element by the Array Index Position
# queries for all documents where the second element in the array dim_cm is greater than 25
> db.inventory.find( { "dim_cm.1": { $gt: 25 } } )

# Query an Array by Array Length
# selects documents where the array tags has 3 elements
> db.inventory.find( { "tags": { $size: 3 } } )
# 查询嵌入式文档的数组
# To populate the inventory collection
> db.inventory.insertMany( [
   { item: "journal", instock: [ { warehouse: "A", qty: 5 }, { warehouse: "C", qty: 15 } ] },
   { item: "notebook", instock: [ { warehouse: "C", qty: 5 } ] },
   { item: "paper", instock: [ { warehouse: "A", qty: 60 }, { warehouse: "B", qty: 15 } ] },
   { item: "planner", instock: [ { warehouse: "A", qty: 40 }, { warehouse: "B", qty: 5 } ] },
   { item: "postcard", instock: [ { warehouse: "B", qty: 15 }, { warehouse: "C", qty: 35 } ] }
  ]);

# Query for a Document Nested in an Array
> db.inventory.find( { "instock": { warehouse: "A", qty: 5 } } )
> db.inventory.find( { "instock": { qty: 5, warehouse: "A" } } )

# Specify a Query Condition on a Field in an Array of Documents
# Use the Array Index to Query for a Field in the Embedded Document
> db.inventory.find( { 'instock.0.qty': { $lte: 20 } } )
# Specify a Query Condition on a Field Embedded in an Array of Documents
> db.inventory.find( { 'instock.qty': { $lte: 20 } } )

# Specify Multiple Conditions for Array of Documents
# A Single Nested Document Meets Multiple Query Conditions on Nested Fields
> db.inventory.find( { "instock": { $elemMatch: { qty: 5, warehouse: "A" } } } )
> db.inventory.find( { "instock": { $elemMatch: { qty: { $gt: 10, $lte: 20 } } } } )
# Combination of Elements Satisfies the Criteria
> db.inventory.find( { "instock.qty": { $gt: 10,  $lte: 20 } } )
> db.inventory.find( { "instock.qty": 5, "instock.warehouse": "A" } )
Update Operations
# 更新单个集合中的文档
# MongoDB中的所有写入操作都是单个文档的级别的原子
> db.collection.updateOne(<filter>, <update>, <options>)
> db.collection.updateMany(<filter>, <update>, <options>)
> db.collection.replaceOne(<filter>, <replacement>, <options>)
# 更新文档示例
# To create and/or populate the inventory collection,
> db.inventory.insertMany( [
   { item: "canvas", qty: 100, size: { h: 28, w: 35.5, uom: "cm" }, status: "A" },
   { item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
   { item: "mat", qty: 85, size: { h: 27.9, w: 35.5, uom: "cm" }, status: "A" },
   { item: "mousepad", qty: 25, size: { h: 19, w: 22.85, uom: "cm" }, status: "P" },
   { item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "P" },
   { item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" },
   { item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" },
   { item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" },
   { item: "sketchbook", qty: 80, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
   { item: "sketch pad", qty: 95, size: { h: 22.85, w: 30.5, uom: "cm" }, status: "A" }
  ]);


# Update Documents in a Collection
# Update a Single Document
> db.inventory.updateOne(
   { item: "paper" },
   {
     $set: { "size.uom": "cm", status: "P" },
     $currentDate: { lastModified: true }
   }
  )
# Update Multiple Documents
> db.inventory.updateMany(
   { "qty": { $lt: 50 } },
   {
     $set: { "size.uom": "in", status: "P" },
     $currentDate: { lastModified: true }
   }
  )

# Replace a Document
> db.inventory.replaceOne(
   { item: "paper" },
   { item: "paper", instock: [ { warehouse: "A", qty: 60 }, { warehouse: "B", qty: 40 } ] }
  )
Delete Operations
# 删除单个集合中的文档
# MongoDB中的所有写入操作都是单个文档的级别的原子
> db.collection.deleteOne()
> db.collection.deleteMany()
# 删除文档示例
# To populate the inventory collection
> db.inventory.insertMany( [
   { item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
   { item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "P" },
   { item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" },
   { item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" },
   { item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" },
  ]);


# Delete All Documents
> db.inventory.deleteMany({})

# Delete All Documents that Match a Condition
> db.inventory.deleteMany({ status : "A" })

# Remove Only One Document that Matches a Condition
> db.inventory.deleteOne( { status: "D" } )
Bulk Write
# 批量执行写入操作
> db.collection.bulkWrite()
> db.collection.insertMany()
# The characters collection
{ "_id" : 1, "char" : "Brisbane", "class" : "monk", "lvl" : 4 },
{ "_id" : 2, "char" : "Eldon", "class" : "alchemist", "lvl" : 3 },
{ "_id" : 3, "char" : "Meldane", "class" : "ranger", "lvl" : 3 }

# The following bulkWrite() performs multiple operations on the collection
> try {
   db.characters.bulkWrite(
      [
         { insertOne :
            {
               "document" :
               {
                  "_id" : 4, "char" : "Dithras", "class" : "barbarian", "lvl" : 4
               }
            }
         },
         { insertOne :
            {
               "document" :
               {
                  "_id" : 5, "char" : "Taeln", "class" : "fighter", "lvl" : 3
               }
            }
         },
         { updateOne :
            {
               "filter" : { "char" : "Eldon" },
               "update" : { $set : { "status" : "Critical Injury" } }
            }
         },
         { deleteOne :
            { "filter" : { "char" : "Brisbane"} }
         },
         { replaceOne :
            {
               "filter" : { "char" : "Meldane" },
               "replacement" : { "char" : "Tanys", "class" : "oracle", "lvl" : 4 }
            }
         }
      ]
   );
  }
  catch (e) {
     print(e);
  }

# The operation returns the following
> {
   "acknowledged" : true,
   "deletedCount" : 1,
   "insertedCount" : 2,
   "matchedCount" : 2,
   "upsertedCount" : 0,
   "insertedIds" : {
      "0" : 4,
      "1" : 5
   },
   "upsertedIds" : {

   }
  }

MongoDB 安装及启动

在MAC上安装及启动
# 安装
# install the mongodb binaries
> brew install mongodb
# create the data directory
> mkdir -p /data/db
> mongo
# 启动
> mongo --port 27017
在WIN上安装及启动
# 安装
# INSTALLLOCATION为自定义安装位置 
> msiexec.exe /q /i mongodb-win32-x86_64-2008plus-ssl-3.4.5-signed.msi ^
            INSTALLLOCATION="C:\Program Files\MongoDB\Server\3.4.5\" ^
            ADDLOCAL="all"
# default: md \data\db
> "C:\Program Files\MongoDB\Server\3.4\bin\mongod.exe" --dbpath d:\test\mongodb\data
> mongod.exe
> mongo.exe
# 配置
# 在bin目录新建starup.bat文件,写入以下命令并保存,便于以后启动,port默认27017
> mongod -dbpath ../data -auth --port 27318  
# 启动
# 启动starup.bat + (mongod.exe)
# 若使用IDE工具操作MongoDB,则每次仅需打开starup.bat文件启动MongoDB
> mongo --port 27318 (default:27017)

//以下为注册为WIN服务,可选
# 管理员身份启动命令行
mongodb\bin + mongod.exe 
> --dbpath=E:\mongodb\data --logpath=E:\mongodb\data\log\mongodb.log --install --serviceName "MongoDB" 
# 启动MongoDB数据库服务,win+R + services.msc +设置为开机启动加入服务后此步可省略 
cmd + netstart MongoDB 
# 监视运行状态
http://localhost:27318
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值