MongoDB—CRUD

时间:2020-08-28 13:05:09   收藏:0   阅读:127

mongodb Collection

命名规范

创建集合

直接插入文档

db.createCollection

https://docs.mongodb.com/v4.2/reference/method/db.createCollection/

格式
db.createCollection( <name>,
   {
     capped: <boolean>,
     autoIndexId: <boolean>,
     size: <number>,
     max: <number>,
     storageEngine: <document>,
     validator: <document>,
     validationLevel: <string>,
     validationAction: <string>,
     indexOptionDefaults: <document>,
     viewOn: <string>,              // Added in MongoDB 3.4
     pipeline: <pipeline>,          // Added in MongoDB 3.4
     collation: <document>,         // Added in MongoDB 3.4
     writeConcern: <document>
   }
)

权限控制

具有 readWrite 内建角色的用户具有上述操作的所有权限,可将角色授予现有用户用来执行上述操作

示例

删除集合

db.collection.drop

格式

db.collection.drop( { writeConcern: <document> } )

Returns

查询集合

查询当前数据库中有哪些集合

show collections

show tables

重命名

db.collection.renameCollection

格式

db.collection.renameCollection(target, dropTarget)

示例

db.rrecord.renameCollection("record")

固定集合

capped collection

具有 固定大小的 存储空间的 集合

特点

限制

创建

db.createCollection

格式

db.createCollection( <name>, { capped:true, size: <number1>, max: <number2> } )
db.runCommand

格式

db.runCommand( "convertToCapped": <name>,  size: <number1> )

检验

db.collection.isCapped
db.collection.isCapped()

返回结果

应用

mongodb CRUD

create read update delete

Create

db.collection.insert

格式

db.collection.insert(
   <document or array of documents>,
   {
     writeConcern: <document>,
     ordered: <boolean>
   }
)

insert 包含 insertOne 和 insertMany

示例

> db.person.insert([
... {
...  name:"lfp",
...  age:18,
...  birth: new Date("1992-10-24")
... },
... {
...  name:"xm",
...  age:19,
...  birth: new Date("1991-01-22")
... }
... ])

db.collection.insertOne

格式

db.collection.insertOne(
   <document>,
   {
      writeConcern: <document>
   }
)

db.collection.insertMany

格式

db.collection.insertMany(
   [ <document 1> , <document 2>, ... ],
   {
      writeConcern: <document>,
      ordered: <boolean>
   }
)

db.collection.save

格式

db.collection.save(
   <document>,
   {
     writeConcern: <document>
   }
)

新版本中有可能被废弃,建议使用 insertOne 或 replaceOne

4.2 版本测试仍可以使用

示例

当插入_id 主键相同的文档时会覆盖

> db.person.save({
...  _id:ObjectId("5f2d16c2cbb6771db2cf3db9"),
...   name:"lfp",
...   age:23,
...   birth:new Date("1992-10-24")
... })
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Read/Query

query an array

db.collection.find

格式
db.collection.find(
   <query>,
   <projection>
)
Returns

返回指向文档的游标

游标 cursor 指向符合查询条件的文档,find 方法实际返回的是指向文档的游标

示例

文档

The bios Example Collection

db.collection.findOne

格式

db.collection.find(
   <query>,
   <projection>
)

Returns

返回文档而非游标

示例

db.bios.findOne(
   {
     $or: [
            { ‘name.first‘ : /^G/ },
            { birth: { $lt: new Date(‘01/01/1945‘) } }
          ]
   }
)

db.collection.findAndModify

db.collection.findOneAndDelete

db.collection.findOneAndReplace

db.collection.findOneAndUpdate

Update

db.collection.update

格式
db.collection.update(
   <query>,
   <update>,
   {
     upsert: <boolean>,
     multi: <boolean>,
     writeConcern: <document>,
     collation: <document>,
     arrayFilters: [ <filterdocument1>, ... ],
     hint:  <document|string>        // Available starting in MongoDB 4.2
   }
)
Returns

返回一个 WriteResult 文档,包含操作的状态

示例

db.collection.updateOne

格式

db.collection.updateOne(
   <filter>,
   <update>,
   {
     upsert: <boolean>,
     writeConcern: <document>,
     collation: <document>,
     arrayFilters: [ <filterdocument1>, ... ],
     hint:  <document|string>        // Available starting in MongoDB 4.2.1
   }
)

Returns

同 update 方法

示例

db.collection.updateMany

格式

db.collection.updateMany(
   <filter>,
   <update>,
   {
     upsert: <boolean>,
     writeConcern: <document>,
     collation: <document>,
     arrayFilters: [ <filterdocument1>, ... ],
     hint:  <document|string>        // Available starting in MongoDB 4.2.1
   }
)

Returns

示例

db.collection.replaceOne

格式

db.collection.replaceOne(
   <filter>,
   <replacement>,
   {
     upsert: <boolean>,
     writeConcern: <document>,
     collation: <document>,
     hint: <document|string>                   // Available starting in 4.2.1
   }
)

Returns

同 updateMany

示例

Delete

db.collection.remove

格式
db.collection.remove(
   <query>,
   <justOne>
)
db.collection.remove(
   <query>,
   {
     justOne: <boolean>,
     writeConcern: <document>,
     collation: <document>
   }
)
Returns

返回一个 WriteResult 包含操作状态

示例

db.collection.deleteOne

格式

db.collection.deleteOne(
   <filter>,
   {
      writeConcern: <document>,
      collation: <document>
   }
)

Returns

返回一个文档,包含

db.collection.deleteMany

格式

db.collection.deleteMany(
   <filter>,
   {
      writeConcern: <document>,
      collation: <document>
   }
)

Returns

同 deleteOne

db.collection.find().pretty()

Operators

Query and Projection Operators

Comparison Operators

$eq

格式

{ field: { $eq: value } }
// 等价于下面的写法
{ field: <value> }

示例

db.inventory.find( { tags: { $eq: [ "A", "B" ] } } )
db.inventory.find( { tags: [ "A", "B" ] } )

db.inventory.find( { "item.name": { $eq: "ab" } } )
db.inventory.find( { "item.name": "ab" } )
$gt

格式

{field: {$gt: value} }

示例

db.inventory.update( { "carrier.fee": { $gt: 2 } }, { $set: { price: 9.99 } } )
$gte

格式

{field: {$gte: value} }
$in

格式

{ field: { $in: [<value1>, <value2>, ... <valueN> ] } }

示例

$lt

格式

{field: {$lt: value} }
$lte

格式

{ field: { $lte: value} }
$ne

格式

 {field: {$ne: value} }
$nin

格式

{ field: { $nin: [ value1, value2 ... valueN ]}

示例

db.inventory.update( { tags: { $nin: [ "appliances", "school" ] } }, { $set: { sale: false } } )

Logical Operators

$and

格式

{ $and: [ { <expression1> }, { <expression2> } , ... , { <expressionN> } ] }

示例

$not

格式

 { field: { $not: { <operator-expression> } } }

示例

$nor

格式

{ $nor: [ { <expression1> }, { <expression2> }, ...  { <expressionN> } ] }

示例


  - 查询条件是:
    1. price存在且不等于1.99 且 sale不为true
    2. price不存在 且 sale 存在且不为true
    3. price存在且不等于1.99 且 sale 不存在
    4. price不存在 且 sale 不存在

- 结合 $exists 操作符使用

  ```sql
  db.inventory.find( { $nor: [ { price: 1.99 }, { price: { $exists: false } },
                               { sale: true }, { sale: { $exists: false } } ] } )
$or

格式

{ $or: [ { <expression1> }, { <expression2> }, ... , { <expressionN> } ] }

示例

db.inventory.find( { $or: [ { quantity: { $lt: 20 } }, { price: 10 } ] } )

为了支持 $or 查询,需要给 quantity 和 price 字段建立索引

db.inventory.createIndex( { quantity: 1 } )
db.inventory.createIndex( { price: 1 } )

Element Operators

$exists

格式

{ field: { $exists: <boolean> } }
$type

格式

{ field: { $type: <BSON type> } }
{ field: { $type: [ <BSON type1> , <BSON type2>, ... ] } }

示例

Evaluation Operators

评估操作符

$expr

格式

{ $expr: { <expression> } }

示例

$jsonSchema
$mod

格式

{ field: { $mod: [ divisor, remainder ] } }

示例

文档

{ "_id" : 1, "item" : "abc123", "qty" : 0 }
{ "_id" : 2, "item" : "xyz123", "qty" : 5 }
{ "_id" : 3, "item" : "ijk123", "qty" : 12 }

查询

db.inventory.find( { qty: { $mod: [ 4, 0 ] } } )
$text

格式

{
  $text:
    {
      $search: <string>,
      $language: <string>,
      $caseSensitive: <boolean>,
      $diacriticSensitive: <boolean>
    }
}

示例

文档

db.articles.createIndex( { subject: "text" } )
db.articles.insert(
   [
     { _id: 1, subject: "coffee", author: "xyz", views: 50 },
     { _id: 2, subject: "Coffee Shopping", author: "efg", views: 5 },
     { _id: 3, subject: "Baking a cake", author: "abc", views: 90  },
     { _id: 4, subject: "baking", author: "xyz", views: 100 },
     { _id: 5, subject: "Café Con Leche", author: "abc", views: 200 },
     { _id: 6, subject: "Сырники", author: "jkl", views: 80 },
     { _id: 7, subject: "coffee and cream", author: "efg", views: 10 },
     { _id: 8, subject: "Cafe con Leche", author: "xyz", views: 10 }
   ]
)
$regex

格式

正则操作符表达式

{ <field>: { $regex: /pattern/, $options: ‘<options>‘ } }
{ <field>: { $regex: ‘pattern‘, $options: ‘<options>‘ } }
{ <field>: { $regex: /pattern/<options> } }

正则对象表达式

{ <field>: /pattern/<options> }

$regex vs. /pattern/ Syntax:{}

$where

3.6版本中 $expr 操作符允许在查询语言中使用聚合表达式,比where执行速度更快,因为不执行 JavaScript 代码,应首选 $expr

格式

{ $where: <JavaScript expression>

示例

文档

{
   _id: 12378,
   name: "Steve",
   username: "steveisawesome",
   first_login: "2017-01-01"
}
{
   _id: 2,
   name: "Anya",
   username: "anya",
   first_login: "2001-02-02"
}

查询

db.players.find( { $where: function() {
   return (hex_md5(this.name) == "9b53e667f30cd329dca1ec9e6a83e994")
} } );

Geospatial Operators

Array Operators

$all

格式

{ <field>: { $all: [ <value1> , <value2> ... ] } }

示例

$elemMatch

格式

{ <field>: { $elemMatch: { <query1>, <query2>, ... } } }

示例

$size

Bitwise Operators

Projection Operators

$
$elemMatch
$slice

Update Operators

https://docs.mongodb.com/manual/reference/operator/update-field/

Field Update Operators

$currentDate
$inc

increments 增长

格式

{ $inc: { <field1>: <amount1>, <field2>: <amount2>, ... } }
$min
$max
$mul
$rename

格式

{$rename: { <field1>: <newName1>, <field2>: <newName2>, ... } }

示例

文档

db.students.insert([
{
  "_id": 1,
  "alias": [ "The American Cincinnatus", "The American Fabius" ],
  "mobile": "555-555-5555",
  "nmae": { "first" : "george", "last" : "washington" }
},
{
  "_id": 2,
  "alias": [ "My dearest friend" ],
  "mobile": "222-222-2222",
  "nmae": { "first" : "abigail", "last" : "adams" }
},
{
  "_id": 3,
  "alias": [ "Amazing grace" ],
  "mobile": "111-111-1111",
  "nmae": { "first" : "grace", "last" : "hopper" }
}
])
$set

格式

{ $set: { <field1>: <value1>, ... } }

若指定子文档或数组中的字段,则使用点表示法

数组

  • 指定 contribs 中第三个元素,则表示为 contribs.2

    {
       ...
       contribs: [ "Turing machine", "Turing test", "Turingery" ],
       ...
    }
    

子文档

  • 指定 last 字段,则表示为 name.last

    指定 number 字段,则表示为 contact.phone.number

    {
       ...
       name: { first: "Alan", last: "Turing" },
       contact: { phone: { type: "cell", number: "111-222-3333" } },
       ...
    }
    

示例

文档

{
  _id: 100,
  sku: "abc123",
  quantity: 250,
  instock: true,
  reorder: false,
  details: { model: "14Q2", make: "xyz" },
  tags: [ "apparel", "clothing" ],
  ratings: [ { by: "ijk", rating: 4 } ]
}

更新操作

db.products.update(
   { _id: 100 },
   { $set:
      {
        quantity:500,
        "details.make":"zzz",
        "tags.1": "rain gear",
        "ratings.0.rating": 2
      }
   }
)
$unset

格式

{ $unset: { <field1>: "", ... } }
$setOnInsert

Array Update Operators

$

示例

$[]

New in version 3.6.

格式

db.collection.updateMany(
   { <query conditions> },
   { <update operator>: { "<array>.$[]" : value } }
)

示例

$[ <identifier> ]

New in version 3.6.

格式

db.collection.updateMany(
   { <query conditions> },
   { <update operator> : { "<array>.$[<identifier>]" : value } },
   { arrayFilters: [ { <identifier>: <condition> } ] }
)

示例

$addToSet
$pop

格式

{ $pop: { <field>: <-1 | 1>, ... } }

示例

文档

{ _id: 1, scores: [ 8, 9, 10 ] }

更新

db.students.update( { _id: 1 }, { $pop: { scores: -1 } } )
$pull

格式

{ $pull: { <field1>: <value|condition>, <field2>: <value|condition>, ... } }

示例

$push

格式

{ $push: { <field1>: <value1>, ... } }

结合修饰符

{ $push: { <field1>: { <modifier1>: <value1>, ... }, ... } }

示例

$pullAll
$each
$position
$slice
$sort

Query Modifiers

$natural

原文:https://www.cnblogs.com/usmile/p/13576779.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!