插入文档
如果当前集合不存在,插入操作将创建集合
插入单个文档
语法:db.collection.insertOne()
db.inventory.insertOne(
{ item: "canvas", qty: 100, tags: ["cotton"], size: { h: 28, w: 35.5, uom: "cm" } }
)
)
如果插入的文档没有携带_id字段,MongoDB会自动生成_id字段值(并且值为ObjectId类型)
插入成功后,会返回_id字段值
查看刚插入的文档:
db.inventory.find( { item: "canvas" } )
插入多个文档
语法:db.collection.insertMany()
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" } }
])
如果插入的文档没有携带_id字段,MongoDB会自动生成_id字段值(并且值为ObjectId类型)
插入成功后,会返回每个文档的_id字段值
查看集合下所有文档:
db.inventory.find( {} )
说明:
- 如果当前集合不存在,则插入操作将创建集合
- 插入的每个文档都需要一个唯一主键,不指定,MongoDB会自动生成_id主键字段值
语法 | 说明 |
---|---|
db.collection.insertOne() | 插入单个文档到集合 |
db.collection.insertMany() | 插入多个文档到集合 |
db.collection.insert() | 插入单个或多个文档到集合 |
查询文档
语法:db.collection.find({},{})
参数1:查询过滤器
参数2:查询结果要显示的字段
案例1:完整匹配查询
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" }
]);
db.inventory.find( { size: { h: 14, w: 21, uom: "cm" } } ) #可以匹配到结果
db.inventory.find( { size: { w: 21, h: 14, uom: "cm" } } ) #无法匹配到结果
完整匹配要求:字段和值一一对应(包括字段顺序)
查询嵌套字段
笔记:
使用嵌套查询,field.nestedField必须在引号内。
使用完整匹配
案例2:
db.inventory.find( { "size.uom": "in" } )
使用查询运算符匹配
语法:{ 《field1》: { 《operator1》: 《value1》 }, … }
案例3:
db.inventory.find( { "size.h": { $lt: 15 } } )
多条件查询-案例4:
db.inventory.find( { "size.h": { $lt: 15 }, "size.uom": "in", status: "D" } )
匹配数组
以下示例按指定顺序查询字段标记值为正好包含两个元素“red”和“blank”的数组的所有文档:
db.inventory.find( { tags: ["red", "blank"] } )
相反,如果希望查找同时包含元素“red”和“blank”的数组,而不考虑数组中的顺序或其他元素,请使用$all运算符:
db.inventory.find( { tags: { $all: ["red", "blank"] } } )
查询dim_cm数组中至少有一个大于25
db.inventory.find( { dim_cm: { $gt: 25 } } )
查询数组dim_cm第二个元素大于25的
db.inventory.find( { "dim_cm.1": { $gt: 25 } } )
更新文档
- db.collection.updateOne(《filter》,《update》,《options》)
- db.collection.updateMany(《filter》,《update》,《options》)
- db.collection.replaceOne(《filter》,《update》,《options》)
{
<update operator>: { <field1>: <value1>, ... },
<update operator>: { <field2>: <value2>, ... },
...
}
示例:
db.inventory.updateOne(
{ item: "paper" },
{
$set: { "size.uom": "cm", status: "P" },
$currentDate: { lastModified: true }
}
)
删除文档
方法 | 说明 |
---|---|
db.collection.deleteOne() | 删除单个文档(就算匹配多项,也只能删除一个) |
db.collection.deleteMany() | 删除匹配的所有文档 |
db.collection.remove() | 删除单个文档或匹配的所有文档 |