MongoDB常用操作

官方文档:https://docs.mongodb.com/manual/reference/operator/

简单

  • use dbName 切换数据库
  • db.getCollectionNames() 列出数据库中的集合们
  • db.collctionName.insert({"name":"wrfly","ID":"wrfly","tags":["tag1","tag2","tag3"]}) 插入数据

查询

  • db.C.find() 查询全部数据

比较类

  • db.inventory.find({"ID":"wrfly"}) 精确查询 IDwrfly 的文档 或者 db.inventory.find( { "ID": { $eq: "wrfly" } } )
  • 同理, $eq 还可以换成 $gt (>), $gte (>=), $lt(<), $lte(<=), $ne(!=), $in(在集合中), $nin(不在集合中)
  • db.inventory.find ( { quantity: { $in: [20, 50] } } ) 查找 quantity在20和50之间(大于20,小于50)的数据

逻辑判断类(与或非)

  • db.inventory.find( { $or: [ { quantity: { $lt: 20 } }, { price: 10 } ] } ) 查询 quantity 小于20或者 price 大于10的数据
  • db.inventory.find( { $and: [ { price: { $ne: 1.99 } }, { price: { $exists: true } } ] } ) 查询 price != 1.99 并且 price 字段存在的数据

db.inventory.find( { $and : [ { $or : [ { price : 0.99 }, { price : 1.99 } ] }, { $or : [ { sale : true }, { qty : { $lt : 20 } } ] } ] } )

- `db.inventory.find( { price: { $not: { $gt: 1.99 } } } )` 查询 price 不大于 1.99 的数据 或者 price 字段不存在的数据
- `db.inventory.find( { $nor: [ { price: 1.99 }, { sale: true } ]  } )` 查询 price != 1.99 && sale == true, 或者 price == 1.99 && sale 字段不存在,或者 price 字段不存在 && sale == true, 或者 price 字段不存在 && sale 字段也不存在 的数据(有点绕,需要认真读一下)

## 元素类
- `db.inventory.find( { qty: { $exists: true} } )` 查询 qty 字段存在的数据

指定元素类型:

- `db.addressBook.find( { "zipCode" : { $type : 2 } } )`
- `db.addressBook.find( { "zipCode" : { $type : "string" } } );`
查询 zipCode 为 string 类型的文档

常用元素类型表:

Type Number Alias Double 1 “double” String 2 “string” Object 3 “object” Array 4 “array” Boolean 8 “bool” Timestamp 17 “timestamp”


[全部类型表](https://docs.mongodb.com/manual/reference/operator/query/type/#available-types)

# 更新

### 字段类
- `$inc` 自增操作
文档:
```json
{
  _id: 1,
  sku: "abc123",
  quantity: 10,
  metrics: {
    orders: 2,
    ratings: 3.5
  }
}

执行了自增操作:

   { sku: "abc123" },
   { $inc: { quantity: -2, "metrics.orders": 1 } }
)

就会变成:

{
   "_id" : 1,
   "sku" : "abc123",
   "quantity" : 8, // 10 -> 8
   "metrics" : {
      "orders" : 3, // 2 -> 3
      "ratings" : 3.5
   }
}
  • $mul 乘法操作 文档:
{ _id: 1, item: "ABC", price: 10.0 }

经过操作:

   { _id: 1 },
   { $mul: { price: 2.0 } }
)

就会变成:

{ _id: 1, item: "ABC", price: 20.0 }
  • $rename 重命名一个字段

_id=1 的文档的 nickname 更名为 alias, cell 更名为 mobile

  • $setOnInsert 只有插入新数据的时候才会更改字段的值,否则不会
  { _id: 1 },
  {
     $set: { item: "apple" },
     $setOnInsert: { defaultQty: 100 }
  },
  { upsert: true }
)
  • $set 设置字段的值 假设有如下文档:
{
  _id: 100,
  sku: "abc123",
  quantity: 250,
  instock: true,
  reorder: false,
  details: { model: "14Q2", make: "xyz" },
  tags: [[ "apparel", "clothing" ],]
  ratings: [ { by: "ijk", rating: 4 } ]
}

那么在执行了下面的操作后:

   { _id: 100 },
   { $set:
      {
        quantity: 500,
        details: { model: "14Q3", make: "xyz" },
        tags: [[ "coats", "outerwear", "clothing" ]]
      }
   }
)

文档就会变成:

{
  _id: 100,
  sku: "abc123",
  quantity: 500,
  instock: true,
  reorder: false,
  details: { model: "14Q3", make: "xyz" },
  tags: [[ "coats", "outerwear", "clothing" ],]
  ratings: [ { by: "ijk", rating: 4 } ]
}
  • $unset 取消这个字段,类似于 unset 一个变量
   { sku: "unknown" },
   { $unset: { quantity: "", instock: "" } }
)

匹配到 { sku: “unknown” } 的文档,并且 unset 他们的 quantity 和 instock 字段。

  • $min 如果字段 要设定的值 小于 当前值,那么就更新字段的值 假设有一个这样的文档: { _id: 1, highScore: 800, lowScore: 200 }

  • $max 如果字段 要设定的值 大于 当前值,那么就更新字段的值 道理同 $min

  • $currentDate 设定字段为当前时间 文档: { _id: 1, status: "a", lastModified: ISODate("2013-10-02T01:11:18.965Z") }

经过操作:

   { _id: 1 },
   {
     $currentDate: {
        lastModified: true,
     },
     $set: {
        status: "D",
        "cancellation.reason": "user request"
     }
   }
)

就会变成:

{
   "_id" : 1,
   "status" : "D",
   "lastModified" : ISODate("2014-09-17T23:25:56.314Z"),
   "cancellation" : {
      "reason" : "user request"
   }
}

数组类

  • $ dolor符号代表搜索到的元素,是一个 placeholder 比如,有个这样的文档:
{ "_id" : 1, "grades" : [ 80, 85, 90 ] }
{ "_id" : 2, "grades" : [ 88, 90, 92 ] }
{ "_id" : 3, "grades" : [ 85, 100, 90 ] }

执行:

   { _id: 1, grades: 80 },
   { $set: { "grades.$" : 82 } }
)

就会把 { _id: 1, grades: 80 } 匹配到的文档的 grades 中的 80 改为 82:

{ "_id" : 1, "grades" : [ 82, 85, 90 ] }

同样的,如果有个这样的文档:

{
  _id: 4,
  grades: [
     { grade: 80, mean: 75, std: 8 },
     { grade: 85, mean: 90, std: 5 },
     { grade: 90, mean: 85, std: 3 }
  ]
}

执行:

   { _id: 4, "grades.grade": 85 },
   { $set: { "grades.$.std" : 6 } }
)

则会把 grade==85 的元素的 std 改为 6:

{
  _id: 4,
  grades: [
    { grade: 80, mean: 75, std: 8 },
    { grade: 85, mean: 90, std: 6 },
    { grade: 90, mean: 85, std: 3 }
  ]
}
  • $addToSet 这个操作会向数组中增加一个元素,当且仅当这个元素不存在与这个数组中。 文档:{ _id: 1, letters: ["a", "b"] }

经过操作:

   { _id: 1 },
   { $addToSet: {letters: [ "c", "d" ] } }
)

就会变成: { _id: 1, letters: [ "a", "b", [ "c", "d" ] ] }, 注意,不是 { _id: 1, letters: ["a", "b", "c", "d"] }

文档:

{ _id: 1, item: "polarizing_filter", tags: [[ "electronics", "camera" ] }]

经过操作:

   { _id: 1 },
   { $addToSet: { tags: ["camera"  } }]
)

没有变化,因为 camera 已经在 tags里面了。

  • $pop 从数组中移除第一个或者最后一个字段 移除第一个:

移除最后一个:

注意,这里是 正负1 的差别

  • $pullAll 移除数组中所有匹配到的值 { _id: 1, scores: [ 0, 2, 5, 5, 1, 0 ] }

  • $pull 移除数组中匹配到的元素 文档:

{
   _id: 1,
   fruits: [ "apples", "pears", "oranges", "grapes", "bananas" ],
   vegetables: [ "carrots", "celery", "squash", "carrots" ]
}
{
   _id: 2,
   fruits: [ "plums", "kiwis", "oranges", "bananas", "apples" ],
   vegetables: [ "broccoli", "zucchini", "carrots", "onions" ]
}

经过操作:

    { },
    { $pull: { fruits: { $in: [ "apples", "oranges" ] }, vegetables: "carrots" } },
    { multi: true }
)

会变成:

{
  "_id" : 1,
  "fruits" : [ "pears", "grapes", "bananas" ],
  "vegetables" : [ "celery", "squash" ]
}
{
  "_id" : 2,
  "fruits" : [ "plums", "kiwis", "bananas" ],
  "vegetables" : [ "broccoli", "zucchini", "onions" ]
}

可以看到,fruits中的 “apples”, “oranges” 都没了, vegetables 中的 “carrots” 也都没了。

  • $pushAll 向数组中一次增加多个元素(重复) 格式:{ $pushAll: { <field>: [ <value1>, <value2>, ... ] } }

  • $push 向数组中增加一个元素

   { _id: 1 },
   { $push: { scores: 89 } }
)

这个操作向 scores 数组中 push 了一个 89.

comments powered by Disqus