📜  MongoDB查询和写入操作命令

📅  最后修改于: 2020-11-23 01:01:44             🧑  作者: Mango

查询和写入操作命令

MongoDB插入命令

它在集合中插入一个或多个文档,还返回包含所有输入状态的文档。 insert方法在内部使用由MongoDB提供的insert命令。

句法:

{
   insert: ,
   documents: [ , , , ... ],
   ordered: ,
   writeConcern: {  },
   bypassDocumentValidation: 
}

参数字段

Field Type Description
insert string It is the name of the collection where we want to insert the element.
documents array It is an array of files that we want to insert into the collection
ordered boolean If it sets to true then it returns the result without inserting any remaining documents listed in the insert array when an insert operation fails, and vice versa
writeConcern document It is a document that defines the write concern of insert command.
bypass
Document
Validation
boolean We can insert the document that does not meet the validation requirement using this field.

例:

让我们将文档插入books集合中:

db.runCommand(
   {
      insert: "books",
      documents: [ { _id: 1, bookname: "MongoDB", status: "sold" } ]
   }
)

MongoDB删除命令

我们可以使用delete命令从集合中删除任何文档。一个删除命令中有多个删除规范。我们不能在上限集合中使用它。删除命令在内部由MongoDB提供的删除方法使用。

句法:

{
   delete: ,
   deletes: [
      { q : , limit : , collation:  },
      { q : , limit : , collation:  },
      { q : , limit : , collation:  },
      ...
   ],
   ordered: ,
   writeConcern: {  }
}

参数字段

Field Type Description
delete string It is the name of the target collection where we want to delete the element.
deletes array It is an array of delete statements on which we want to perform the delete operation.
ordered boolean If it sets to true then it returns the result without inserting any remaining documents listed in the insert array when an insert operation fails, and vice versa
writeConcern document It is a document that defines the write concern of the delete command.
q document It is the query that matches to delete.
limit integer We can limit the matching document to delete using this field. Specify 0 to delete all matching documents and vice versa.
collation document It is an optional field and used to define the collation used for the operation.
Syntax:
collation: {
   locale: ,
   caseLevel: ,
   caseFirst: ,
   strength: ,
   numericOrdering: ,
   alternate: ,
   maxVariable: ,
   backwards: 
}

例子:

下面的示例通过指定限制2,从书库中删除状态为A的文档。

db.runCommand(
   {
      delete: "books",
      deletes: [ { q: { status: "A" }, limit: 1 } ]
   }
)

MongoDB更新命令

update命令对集合中的文档进行更改。它包含多个更新语句。 MongoDB驱动程序提供的更新方法使用它。

句法:

db.runCommand(
   {
      update: ,
      updates: [
         {
           q: ,
           u: ,      // Changed in MongoDB 4.2,
           upsert: ,
           multi: ,
           collation: ,
           arrayFilters: ,
           hint:         // Available starting in MongoDB 4.2
         },
         ...
      ],
      ordered: ,
      writeConcern: {  },
      bypassDocumentValidation: 
   }
)

命令字段:

Field Type Description
update string It is the name of the target collection where we want to update the array.
updates array It is the array of update statements to perform the update operation on the given collection.
ordered boolean It is an optional field if it is set to true. It will return the result without performing the remaining update operation and vice versa.
writeConcern document It is a document that expresses the write concern of the update command. It describes the level of acknowledgment requested from MongoDB for write operations to a standalone MongoDB.
bypass
Document
Validation
booleanIt enables the update operation to bypass document validation.
q document It is the query that matches the documents we want to update.
u document It is the document where the update operator expressions are stored.
upsert boolean If this field is set to true, then it performs an insert operation if no document matches the query.
multi boolean It this field is set to true; it will update all the documents that meet the query criteria.
collation document It specifies language-specific rules for string comparison.
Syntax:
collation: {
   locale: ,
   caseLevel: ,
   caseFirst: ,
   strength: ,
   numericOrdering: ,
   alternate: ,
   maxVariable: ,
   backwards: 
}
arrayfilters array It is an array of documents that describe which array elements we want to modify.
hint string/
document
It is a document that specifies the index to use to support the query predicate.

例:

让我们创建一个学生的收藏集

Db.students.insertMany([
   { _id: 1, student: "john", status: "Pending", points: 0, misc1: "note to self: confirm status", misc2: "Need to activate" },
   { _id: 2, student: "Michael", status: "D", points: 59, misc1: "reminder: ping me at 100pts", misc2: "Some random comment" },
])

run命令使用$ set和$ inc运算符更新成员等于“ john”的文档的状态。

db.runCommand(
   {
      update: "students",
      updates: [
         {
           q: { student: "john" }, u: { $set: { status: "A" }, $inc: { points: 1 } }
         }
      ],
      ordered: false,
      writeConcern: { w: "majority", wtimeout: 5000 }
   }
)

MongoDB find命令

find命令用于执行查询,并返回第一组结果和可以用来构造游标的游标ID。

句法:

db.runCommand(

   {
      "find": ,
      "filter": ,
      "sort": ,
      "projection": ,
      "hint": ,
      "skip": ,
      "limit": ,
      "batchSize": ,
      "singleBatch": ,
      "comment": ,
      "maxTimeMS": ,
      "readConcern": ,
      "max": ,
      "min": ,
      "returnKey": ,
      "showRecordId": ,
      "tailable": ,
      "oplogReplay": ,
      "noCursorTimeout": ,
      "awaitData": ,
      "allowPartialResults": ,
      "collation": 
   }
)

命令字段:

Field Type Description
find string In this field, we can define the name of the collection.
filter document It filters the query.
sort document It is a document that contains the sorting details of the query.
projection document It is the document that contains the projection specification to determine which fields to include in the returned documents.
hint string It is a document that specifies the index name as the string or the index key pattern.
skip positive integer This filed contains the number of documents to be skipped.
limit Non-negative integer We can set the maximum number of documents we want to return.
batchSize Non-negative integer It contains the number of documents we want to return in the first batch.
singleBatch boolean It contains the details of whether to close the cursor after the first batch of the result.
maxTimeMS +ve integer We can set the time limit for the processing operation on the cursor.
readConcern document It specifies the read concern level.
ReadConcern: { level:  }
max document It contains the upper bound for the given index.
min boolean It contains the lower bound for the given index.
returnKey boolean If it is true, return only the index keys in the resulting documents.
showRecordID boolean It is used to return the record identifier for each document.
tailable boolean It returns a tailable cursor for a capped collection.
awaitData boolean It is used to temporarily block the getMore command on the cursor.
oplogReplay boolean It is a command used for replaying a replica set’s oplog. For example –
{ find: "data", oplogReplay: true, filter: 
{ ts: { $gte: new Timestamp(1514764800, 0) } } }
noCursorTimeout boolean This filed to prevent the server from timing out idle cursors.
allowPartialResults boolean This field prevents throwing an error if some shards are unavailable.
collation document It specifies the collation for the operations
Syntax:
collation: {
   locale: ,
   caseLevel: ,
   caseFirst: ,
   strength: ,
   numericOrdering: ,
   alternate: ,
   maxVariable: ,
   backwards: 
}

例:

在下面的示例中,该命令按名称字段对结果集中的文档进行排序,并限制六个文档的结果集。

db.runCommand(
   {
     find: "restaurants",
     filter: { rating: { $gte: 9 }, cuisine: "American" },
     projection: { name: 1, rating: 1, address: 1 },
     sort: { name: 1 },
     limit: 6
   }
)

MongoDB findAndModify命令

它一次修改并返回一个文档。返回的文档默认不包含对更新所做的修改。我们需要使用new选项返回修改后的文档。

句法:

{
  findAndModify: ,
  query: ,
  sort: ,
  remove: ,
  update: , // Changed in MongoDB 4.2
  new: ,
  fields: ,
  upsert: ,
  bypassDocumentValidation: ,
  writeConcern: ,
  collation: ,
  arrayFilters: 
}

指令栏位

Field Type Description
query document The query field contains the same query selectors as used in the db.collection.find() method.
sort document It defines the sort order of the document.
remove boolean This field removes the document specified in the query field.
update document/ array It will update the specified document.
new boolean If it sets to true, it will return the modified document rather than the original one.
fields document It is a subset of the fields to return. It specifies an inclusion of field with value 1.
fields: { : 1, : 1, ... }
upsert boolean It is used with the updated field. If it is true, it creates a new document and updates a single document that matches the query. The default value of this filed is false.
bypass
Document
Validation
boolean It enables findAndModify to bypass document validation during the process.
writeConcern document It is a document that expresses the write concern for the command.
maxTimeMS integer It declares the time limit for the operation.
FindAndModify String This field contains the collection against which we have to run the command.
collation The collation field allows users to specify language-specific rules for string comparison.
Syntax:
collation: {
   locale: ,
   caseLevel: ,
   caseFirst: ,
   strength: ,
   numericOrdering: ,
   alternate: ,
   maxVariable: ,
   backwards: 
}
arrayFilters array It is the array of filter documents that determine that defines which array elements will be modified for the update operation.

例:

               db.runCommand(
   {
     findAndModify: "book",
     query: { name: "MongoDB" },
     sort: { rating: 4 },
     update: { $inc: { price: 1 } },
     upsert: true
   }
 )