This article is the first article in the series on getting started with MongoDB. In this article, we will explain the basic operations of adding, deleting, modifying, and querying MongoDB. After learning this article, the reader will master the basic additions, modifications to MongoDB's collection documents. Delete and query operations based on various conditions.
This article will continue to be revised and updated. For the latest content, please refer to the Program Ape Growth Project on my GITHUB . Welcome to Star. For more exciting content, please follow me .
Insert document
In the MongoDB shell, there are two methods for inserting documents:
- Use
db.collection.insertOne()
insert a single document - Use
db.collection.insertMany()
insert multiple documents
When inserting a document, if the collection does not exist, the insert operation will automatically create the collection . If the document does not have _id
field, MongoDB will automatically add a _id
field of type ObjectId
.
In MongoDB, each document needs a unique
_id
field as the primary key. If the_id
field is not specified when inserting, the MongoDB driver will automatically generate a field of typeObjectId
The_id
field.
ObjectId
is a fast-generated, ordered, 12-byte unique value containing:
- A 4-byte timestamp representing the creation time of the ObjectId, the value is a Unix timestamp (seconds)
- A 5-byte random value that is generated only once per process and is unique to each server and process
- A 3-byte auto increment, initially a random number
use sample_mflix
// 插入单个文档
db.movies.insertOne(
{
title: "The Favourite",
genres: [ "Drama", "History" ],
runtime: 121,
rated: "R",
year: 2018,
directors: [ "Yorgos Lanthimos" ],
cast: [ "Olivia Colman", "Emma Stone", "Rachel Weisz" ],
type: "movie"
}
)
// 插入多个文档
db.movies.insertMany([
{
title: "Jurassic World: Fallen Kingdom",
genres: [ "Action", "Sci-Fi" ],
runtime: 130,
rated: "PG-13",
year: 2018,
directors: [ "J. A. Bayona" ],
cast: [ "Chris Pratt", "Bryce Dallas Howard", "Rafe Spall" ],
type: "movie"
},
{
title: "Tag",
genres: [ "Comedy", "Action" ],
runtime: 105,
rated: "R",
year: 2018,
directors: [ "Jeff Tomsic" ],
cast: [ "Annabelle Wallis", "Jeremy Renner", "Jon Hamm" ],
type: "movie"
}
])
In addition to the commonly used insertOne
and insertMany
methods, you can also insert documents in the following ways
-
db.collection.bulkWrite()
mate
upsert: true
option-
db.collection.updateOne()
-
db.collection.updateMany()
-
db.collection.findAndModify()
-
db.collection.findOneAndUpdate()
-
query document
The most basic query methods are db.collection.find()
and db.collection.findOne()
, insert the following documents in MongoDB
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" }
]);
Query all documents in Collection
// 等价 SQL:SELECT * FROM inventory
db.inventory.find({})
// 等价 SQL:SELECT * FROM inventory LIMIT 1
db.inventory.findOne({})
Specify query conditions
Equivalent query
// 等价 SQL:SELECT * FROM inventory WHERE status = "D"
db.inventory.find({status: "D"})
// 等价 SQL:SELECT * FROM inventory WHERE status != "D"
db.inventory.find({ status: { $ne: "D" } })
IN query
// 等价 SQL:SELECT * FROM inventory WHERE status in ("A", "D")
db.inventory.find({status: { $in: ["A", "D"]}})
// 等价 SQL: SELECT * FROM inventory WHERE status NOT IN ("A", "D")
db.inventory.find({ status: { $nin: ["A", "D"] } })
range query
// SQL: SELECT * FROM inventory WHERE qty >= 50 AND qty < 100
db.inventory.find({ qty: { $gte: 50, $lt: 100 } })
The comparison operators support these: $lt
, $gt
, $gte
, $lte
AND query
// SQL:SELECT * FROM inventory WHERE status = "A" AND qty < 30
db.inventory.find({ status: "A", qty: { $lt: 30 } })
OR query
// SQL:SELECT * FROM inventory WHERE status = "A" OR qty < 30
db.inventory.find({ $or: [ { status: "A"}, { qty: { $lt: 30 } } ] })
Use AND and OR together
// SQL: SELECT * FROM inventory WHERE status = "A" AND ( qty < 30 OR item LIKE "p%" )
db.inventory.find({
status: "A",
$or: [ { qty: { $lt: 30 } }, { item: /^p/ } ]
})
NOT
// 查询 qty 模 5 值为 1 的所有文档,这里匹配的 qty 可能值为 1, 6, 11, 16 等
db.inventory.find({ qty: { $mod: [5, 1] } })
// 查询 qty 模 5 值部位 1 的所有文档,可能值为2, 3, 4, 5, 7, 8, 9, 10, 12 等
db.inventory.find({ qty: { $not: { $mod: [5, 1] } } })
Query nested documents
Query all documents with size
equal to { h: 14, w: 21, uom: "cm" }
db.inventory.find( { size: { h: 14, w: 21, uom: "cm" } } )
Query all documents with size
in uom
equal to in
db.inventory.find( { "size.uom": "in" } )
query array
Insert the following document in MongoDB
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 ] }
]);
The following example queries documents for all fields tags
whose value contains only the elements "red" and "blank" (in the same order)
db.inventory.find({ tags: ["red", "blank"]})
If you only want to query for both "red" and "blank" values, and don't care about sorting or whether the array contains other elements, you can use the $all
operator
db.inventory.find({ tags: { $all: ["red", "blank"] } })
Query tags
Documents containing "red"
db.inventory.find({ tags: "red" })
Query all dim_cm
all documents that contain at least one greater than the value 25
db.inventory.find({ dim_cm: { $gt: 25} })
Query all dim_cm
all documents that contain at least one value greater than 15 or less than 20
db.inventory.find({ dim_cm: { $gt: 15, $lt: 20 } })
Query all dim_cm
all documents containing at least one value greater than 22 and less than 30
db.inventory.find({ dim_cm: { $elemMatch: { $gt: 22, $lt: 30} } })
The second value of the query array dim_cm
is greater than 25
db.inventory.find({ "dim_cm.1": { $gt: 25 }})
Query array tags
all documents with 3 elements
db.inventory.find({ "tags": { $size: 3 } })
The query returns the specified field
By default, MongoDB's query will return all fields in the matching document, through projection
can return the specified field.
Returns the specified field
// SQL: SELECT _id, item, status FROM inventory WHERE status = "A"
db.inventory.find({ status: "A" }, { item: 1, status: 1 })
The query result will automatically return the _id
field, which can be actively eliminated by setting _id: 0
.
// SQL: SELECT item, status FROM inventory WHRE status = "A"
db.inventory.find( { status: "A" }, { item: 1, status: 1, _id: 0 } )
Exclude specified fields
db.inventory.find({ status: "A" }, { status: 0, instock: 0 })
Returns the specified element in the array
Use the $slice
operator to return the instock
last element in the array
db.inventory.find({ status: "A" }, { item: 1, status: 1, instock: { $slice: -1 } })
Query value is NULL or missing field
In MongoDB, different query operator pairs null
are handled differently. Insert the following document in MongoDB
db.inventory.insertMany([
{ _id: 1, item: null },
{ _id: 2 }
])
Equivalent query
Query item
for all documents with the value null
or without the item
field
db.inventory.find({ item: null })
type checking
Query all documents whose value is item
null
db.inventory.find({ item: { $type: 10} })
Here$type = 10
corresponds to the BSON typeNull
Existence check
Query all documents that do not contain the field item
db.inventory.find({ item: { $exists: false } })
Query all documents that contain the item field, but the value is null
db.inventory.find({ item: { $eq: null, $exists: true } })
Limit the number of query results
// 只查询 3 条数据
db.inventory.find({}).limit(3)
// 从第 2 条开始,查询 3 条数据
db.inventory.find({}).limit(3).skip(2)
sort
The sorting direction 1
is the positive order, and -1
is the reverse order.
db.inventory.find({}).sort({item: 1, qty: -1})
Query the number of documents in the collection
This method is used to query the number of documents matching the condition. The syntax is
db.collection.count(query, options)
Example
db.orders.count( { ord_dt: { $gt: new Date('01/01/2012') } } )
Unique value distinct of the query field
Query the unique value of a field in a collection, the syntax is
db.collection.distinct(field, query, options)
Appendix: Supported Query Operators
category | operator | use |
---|---|---|
Comparison | $eq | Equivalence judgment |
Comparison | $gt | greater than a certain value |
Comparison | $gte | greater than or equal to a certain value |
Comparison | $in | The current value is in the array |
Comparison | $lt | less than a certain value |
Comparison | $lte | less than or equal to a certain value |
Comparison | $ne | not equal to a value |
Comparison | $nin | The current value is no longer in the array |
Logical | $and | AND |
Logical | $not | Invert query conditions |
Logical | $nor | All query conditions do not match |
Logical | $or | OR |
Element | $exists | Field Existence Check |
Element | $type | Field type checking |
Evaluation | $expr | Use aggregate syntax in query expressions |
Evaluation | $jsonSchema | Validates that the document conforms to the specified JSON model |
Evaluation | $mod | modulo the field value |
Evaluation | $regex | Select documents matching regular expression |
Evaluation | $text | perform a text search |
Evaluation | $where | JavaScript expression matching |
Geospatial | $geoIntersects | Geographic Coordinate Matching |
Geospatial | $geoWithin | Geographic Coordinate Matching |
Geospatial | $near | Geographic Coordinate Matching |
Geospatial | $nearSphere | Geographic Coordinate Matching |
Array | $all | Matches an array containing all elements specified in the query |
Array | $elemMatch | If the elements in the array match the expression, return the document |
Array | $size | Select documents with an array size of size |
Bitwise | $bitsAllClear | binary match |
Bitwise | $bitsAllSet | binary match |
Bitwise | $bitsAnyClear | binary match |
Bitwise | $bitsAnySet | binary match |
Miscellaneous | $comment | Add a comment to the query |
Miscellaneous | $rand | Randomly generate a floating point value between 0-1 |
update documentation
There are three commonly used document update methods:
-
db.collection.updateOne(<filter>, <update>, <options>)
Update a single document -
db.collection.updateMany(<filter>, <update>, <options>)
Update multiple documents -
db.collection.replaceOne(<filter>, <update>, <options>)
replace a single document
Here we take the updateOne()
method as an example to explain, the updateOne()
method syntax is as follows
db.collection.updateOne(
<filter>, // 要更新的文档筛选条件
<update>, // 文档更新命令
{
upsert: <boolean>, // 设置为 true 时,如果 filter 没有匹配到文档,则自动新增文档
writeConcern: <document>,
collation: <document>,
arrayFilters: [ <filterdocument1>, ... ],
hint: <document|string> // Available starting in MongoDB 4.2.1
}
)
Updated documentation for item=paper
db.inventory.updateOne(
{ item: "paper" },
{
$set: { "size.uom": "cm", status: "P" },
$currentDate: { lastModified: true }
}
)
The update operator is as follows
-
$set
操作符指定了要更新匹配文档的size.uom
cm
,status
p
-
$currentDate
operator is used to update thelastModified
field is the current date, if thelastModified
field does not exist, it will be created automatically
Update the document, or add it if it doesn't exist
db.restaurant.updateOne(
{ "name" : "Pizza Rat's Pizzaria" },
{ $set: {"_id" : 4, "violations" : 7, "borough" : "Manhattan" } },
{ upsert: true }
);
More field operators are as follows
operator | use |
---|---|
$currentDate | Set the field value to the current date, which can be a date or a timestamp |
$inc | Add a value to the field's value |
$min | Update only if the specified value is less than an already existing value |
$max | Update only if the specified amount is greater than the existing value |
$mul | Multiply the value of a field by a numeric value |
$rename | Rename the specified field |
$set | Set the field value to update in the document |
$setOnInsert | If the current operation adds a new document, set the value of the field. This operator has no effect if the update operation only modifies an existing document |
$unset | Remove the specified field from the document |
In addition to the three commonly used methods, the following methods can also be used to update documents
-
db.collection.findOneAndReplace()
. -
db.collection.findOneAndUpdate()
. -
db.collection.findAndModify()
. -
db.collection.bulkWrite()
.
delete document
In MongoDB, documents are usually deleted using
delete all documents
db.inventory.deleteMany({})
Delete all documents matching the criteria
db.inventory.deleteMany({ status : "A" })
Delete a document that matches a condition
db.inventory.deleteOne( { status: "D" } )
In addition to the two commonly used methods, you can also delete documents in the following ways
db.collection.findOneAndDelete()
.findOneAndDelete() provides a
sort
option that allows deleting the first document that matches after sorting by the specified collationdb.collection.findAndModify()
.db.collection.findAndModify()
provides asort
option that allows deleting the first document that matches after sorting by the specified collation-
db.collection.bulkWrite()
.
Bulk write operations
MongoDB provides the ability to perform batch write operations on a single Collection, using the db.collection.bulkWrite()
method to implement batch insert, update, and delete operations.
In-order and out-of-order operations
Batch write operations can be ordered ( ordered
) or unordered ( unordered
). For ordered operations, MongoDB will perform operations serially. Error, MongoDB will return directly, and subsequent operations will not be performed. Out-of-order operations do not guarantee this behavior, and in the event of an error, MongoDB will continue to process the remaining documents.
For sharded collections, performing ordered batch operations is often slower because each operation must wait for the previous operation to complete. By default, bulkWrite()
performs in-order operation, and out-of-order operation can be enabled by setting the ordered: false
option.
bulkWrite() method
bulkWrite()
Support the following write operations
Suppose a collection named characters
contains the following documents
{ "_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()
method performs multiple operations on the collection
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 }
}
}
]
);
The operation returns the following
{
"acknowledged" : true,
"deletedCount" : 1,
"insertedCount" : 2,
"matchedCount" : 2,
"upsertedCount" : 0,
"insertedIds" : {
"0" : 4,
"1" : 5
},
"upsertedIds" : {
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。