MongoDB之文档CRUD
文档 CRUD 指对文档的创建、查询、更新和删除。
创建文档
使用插入操作向一个集合中添加文档时,如果目标集合当前并不存在,执行操作会自动创建该集合。
MongoDB 提供了以下三个方法来向集合中插入文档:
db.collection.insert()
db.collection.insertOne() // MongoDB 3.2 以上版本
db.collection.insertMany() // MongoDB 3.2 以上版本
在 MongoDB 中,插入操作只能指定一个集合作为目标,并且所有的写操作在单个文档的级别上都是原子性的。
例如下面示例了向 customer 集合中插入一个新文档,如果未指定新文档的 _id 字段,MongoDB 会使用一个 ObjectId 值作为 _id 字段的值,并将其添加到新文档中。
> db.customer.insertOne({name:"lisa",age:27,features:{height:178,weight:63,gender:"female"},hobby:["yoga","cartoon","movie"]})
{
"acknowledged" : true,
"insertedId" : ObjectId("5bcfeb7542f5fcf5f319f0d9")
}
使用 db.collection.insertMany() 方法可以一次性地向集合插入多个文档,传入一个文档数组作为方法的参数即可。
> db.customer.insertMany([{name:"lisa",age:27,features:{height:178,weight:63},hobby:["yoga","cartoon","movie"]},{name:"tracy",age:23,features:{height:168,weight:55},hobby:["yoga","music","movie"]}])
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("5bd00f96c90c1f1d66f50312"),
ObjectId("5bd00f96c90c1f1d66f50313")
]
}
查询文档
MongoDB 提供了下面两个方法用来查询指定集合内部的文档:
db.collection.find()
db.collection.findOne()
查询所有文档
如果你想要查询获取指定集合内的所有文档,你需要传递一个空文档对象作为find() 方法的查询过滤器参数,这个查询过滤器决定了查询获取到的文档应该匹配的条件。
> db.customer.find({}).pretty()
{
"_id" : ObjectId("5bd00f96c90c1f1d66f50312"),
"name" : "lisa",
"age" : 27,
"features" : {
"height" : 178,
"weight" : 63
},
"hobby" : [
"yoga",
"cartoon",
"movie"
]
}
{
"_id" : ObjectId("5bd00f96c90c1f1d66f50313"),
"name" : "tracy",
"age" : 23,
"features" : {
"height" : 168,
"weight" : 55
},
"hobby" : [
"yoga",
"music",
"movie"
]
}
该操作相当于关系型数据库中的 SELECT * FROM customer 查询SQL。
指定等式条件
在查询过滤器文档对象中使用 <field>:<value>指定等式条件,来限制只查询字段 <field> 的值等于<value> 的文档。
例如下面这个例子,查询 customer 集合中所有 name 字段值等于 "tracy" 的文档。
> db.customer.find({name:"tracy"}).pretty()
{
"_id" : ObjectId("5bd00f96c90c1f1d66f50313"),
"name" : "tracy",
"age" : 23,
"features" : {
"height" : 168,
"weight" : 55
},
"hobby" : [
"yoga",
"music",
"movie"
]
}
该操作相当于关系型数据库中的 SELECT * FROM customer WHERE name = "tracy" 查询SQL。
当查询字段 <field> 的值是一个文档对象时,查询示例如下:
> db.customer.find({name:"tracy"}).pretty()
{
"_id" : ObjectId("5bd00f96c90c1f1d66f50313"),
"name" : "tracy",
"age" : 23,
"features" : {
"height" : 168,
"weight" : 55
},
"hobby" : [
"yoga",
"music",
"movie"
]
}
注意:在使用等式条件进行文档查询过滤时,如果匹配的字段值是一个内嵌的文档对象,需要查询结果中该字段的文档内容与过滤器中该字段值的文档内容完全匹配,当然也包括文档内各个字段的顺序,
使用查询操作符
使用查询操作符指定查询过滤器文档对象查询条件的基本语法结构如下:
{ <field1>: { <operator1>: <value1> }, ... }
在 MongoDB 中,常用的查询操作符列举见下表:
Category | Name | Description |
Comparison | $eq | Matches values that are equal to a specified value. |
$gt | Matches values that are greater than a specified value. | |
$gte | Matches values that are greater than or equal to a specified value. | |
$in | Matches any of the values specified in an array. | |
$lt | Matches values that are less than a specified value. | |
$lte | Matches values that are less than or equal to a specified value. | |
$ne | Matches all values that are not equal to a specified value. | |
$nin | Matches none of the values specified in an array. | |
Logical | $and | Joins query clauses with a logical AND returns all documents that match the conditions of both clauses. |
$not | Inverts the effect of a query expression and returns documents that do not match the query expression. | |
$nor | Joins query clauses with a logical NOR returns all documents that fail to match both clauses. | |
$or | Joins query clauses with a logical OR returns all documents that match the conditions of either clause. | |
Element | $exists | Matches documents that have the specified field. |
$type | Selects documents if a field is of the specified type. | |
Evaluation | $expr | Allows use of aggregation expressions within the query language. |
$jsonSchema | Validate documents against the given JSON Schema. | |
$mod | Performs a modulo operation on the value of a field and selects documents with a specified result. | |
$regex | Selects documents where values match a specified regular expression. | |
$text | Performs text search. | |
$where | Matches documents that satisfy a JavaScript expression. | |
Geospatial | $geoIntersects | Selects geometries that intersect with a GeoJSON geometry. The 2dsphere index supports$geoIntersects. |
$geoWithin | Selects geometries within a bounding GeoJSON geometry. The 2dsphere and 2d indexes support $geoWithin. | |
$near | Returns geospatial objects in proximity to a point. Requires a geospatial index. The 2dsphereand 2d indexes support $near. | |
$nearSphere | Returns geospatial objects in proximity to a point on a sphere. Requires a geospatial index. The 2dsphere and 2d indexes support $nearSphere. | |
Array | $all | Matches arrays that contain all elements specified in the query. |
$elemMatch | Selects documents if element in the array field matches all the specified $elemMatchconditions. | |
$size | Selects documents if the array field is a specified size. | |
Bitwise | $bitsAllClear | Matches numeric or binary values in which a set of bit positions all have a value of 0. |
$bitsAllSet | Matches numeric or binary values in which a set of bit positions all have a value of 1. | |
$bitsAnyClear | Matches numeric or binary values in which any bit from a set of bit positions has a value of 0. | |
$bitsAnySet | Matches numeric or binary values in which any bit from a set of bit positions has a value of 1. | |
Comments | $comment | Adds a comment to a query predicate. |
Projection | $ | Projects the first element in an array that matches the query condition. |
$elemMatch | Projects the first element in an array that matches the specified $elemMatchcondition. | |
$meta | Projects the document’s score assigned during $text operation. | |
$slice | Limits the number of elements projected from an array. Supports skip and limit slices. |
例如下面这个例子,获取 customer 集合中所有 name 字段值等于 "tracy" 或者 "lisa" 的文档。
> db.customer.find({name:{$in:["tracy","lisa"]}})
或者也可以使用 $or 操作符实现相同的功能,查询语句如下:
> db.customer.find({$or:[{name:"tracy"},{name:"lisa"}]})
该操作相当于关系型数据库中的 SELECT * FROM customer WHERE name IN ( "tracy","lisa" ) 查询SQL。
再举一个更复杂的例子,获取 customer 集合中所有 age < 25 并且 height > 165 或者 hobby 字段值中包含 "yoga" 的文档。
> db.customer.find({age:{$lte:25},$or:[{'features.height':{$gt:165}},{hobby:{$in:["yoga"]}}]})
查询内嵌文档
上一篇: Flink 灵魂两百问,这谁顶得住?
下一篇: 芹菜区别:本芹和如何区分