1、db.collection.find(query, projection)
查找文档
1.1 语法、参数说明
db.collection.find(query, projection)
参数说明:
参数 | 类型 | 说明 |
query | document | 可选的。使用查询操作符指定查询条件。若要返回集合中的所有文档,请忽略此参数或传递一个空文档({})。 |
projection | document | 可选的。指定查询结果文档中的字段。若要返回匹配文档中的所有字段,请忽略此参数 |
projection 参数: { <field1>: <value>, <field2>: <value> ... }
Projection | 详情 |
<field>: <1 or true> | 指定包含的字段 |
<field>: <0 or false> | 指定排除字段 |
"<field>.$": <1 or true> | 通过数组投影操作符$,可以指定返回数组字段的元素 |
<field>: <array projection> | 使用数组投影操作符$elemMatch, $slice指定要包含的数组元素,从而排除不符合表达式的元素 |
<field>: <$meta expression> | 使用$meta操作符表达式指定包含每个文档可用的元数据 |
<field>: <aggregation expression> | 指定投影字段的值,从MongoDB 4.4开始,通过使用聚合表达式和语法,包括字面量和聚合变量,你可以投射新字段或用新值投射现有字段。 |
1.2 行为表现:
# _id字段默认包含在返回的文档中,除非您在投影中显式地指定_id: 0以抑制该字段。
# 投影不能同时有 包含 和 排除 两种显示指定,_id字段除外。在显式排除字段的投影中,_id字段是唯一可以显式包含的字段,在显式包含字段的投影中,_id字段是唯一可以显式排除的字段。
1.3 例子
## 准备数据
## bios集合结构
{
"_id" : <value>,
"name" : { "first" : <string>, "last" : <string> }, // embedded document
"birth" : <ISODate>,
"death" : <ISODate>,
"contribs" : [ <string>, ... ], // Array of Strings
"awards" : [
{ "award" : <string>, year: <number>, by: <string> } // Array of embedded documents
...
]
}
##1 查询所有
db.bios.find()
##2 相等条件
# _id = 5
db.bios.find( { _id: 5 } )
# 嵌套文档查询 name.last = "Hopper"
db.bios.find( { "name.last": "Hopper" } )
##3 使用操作符
# 使用 $in 操作符查找 _id等于5或ObjectId("507c35dd8fada716c89d0013")的文档
db.bios.find(
{ _id: { $in: [ 5, ObjectId("507c35dd8fada716c89d0013") ] } }
)
# 用 $gt 操作符查找 birth大于new Date('1950-01-01')的所有文档
db.bios.find( { birth: { $gt: new Date('1950-01-01') } } )
# 使用 $regex 操作符查找 name.last 以字母N开始的文档(类似“like N%”)
# 正则表达式
db.bios.find(
{ "name.last": { $regex: /^N/ } }
)
# 组合比较操作符
# 查找出生日期介于日期(' 194001-01 ')和日期('1960-01-01')之间的文档
db.bios.find( { birth: { $gt: new Date('1940-01-01'), $lt: new Date('1960-01-01') } } )
## 4 查询数组
#contribs 字段是数组
#contribs数组包含元素"UNIX 的文档
db.bios.find( { contribs: "UNIX" } )
#包含元素"ALGOL"或"Lisp"的文档
db.bios.find( { contribs: { $in: [ "ALGOL", "Lisp" ]} } )
# 同时包含两个元素"ALGOL"和"Lisp"的文档
db.bios.find( { contribs: { $all: [ "ALGOL", "Lisp" ] } } )
# $size操作符,返回 contrib的数组大小为4的文档
db.bios.find( { contribs: { $size: 4 } } )
## 5 查询文档数组
# awards 是文档数组
#返回 awards数组中,存在award字段等于“Turing Award”的文档
db.bios.find(
{ "awards.award": "Turing Award" }
)
#使用$elemMatch操作符在一个数组元素上指定多个条件
# 返回 awards数组中 , 存在 奖场等于“图灵奖”并且year大于1980 的文档
db.bios.find(
{ awards: { $elemMatch: { award: "Turing Award", year: { $gt: 1980 } } } }
)
### 6 投影 Projections
#指定要返回的字段。参数只包含include或exclude参数,而不是两者都包含,除非是_id字段
#只返回name字段、contribs字段和_id字段
db.bios.find( { }, { name: 1, contribs: 1 } )
#返回除 name 嵌入文档中的 first 字段和 birth 字段外的所有字段
db.bios.find(
{ contribs: 'OOP' },
{ 'name.first': 0, birth: 0 }
)
# 只返回name字段和contribs字段,排除了 _id 字段
db.bios.find(
{ },
{ name: 1, contribs: 1, _id: 0 }
)
# 返回name 嵌入文档中的 last字段和contribs数组的前两个元素:
db.bios.find(
{ },
{ _id: 0, 'name.last': 1, contribs: { $slice: 2 } } )
# 使用聚合投影
db.bios.find(
{ },
{
_id: 0,
name: {
$concat: [
{ $ifNull: [ "$name.aka", "$name.first" ] },
" ",
"$name.last"
]
},
birth: 1,
contribs: 1,
awards: { $cond: { if: { $isArray: "$awards" }, then: { $size: "$awards" }, else: 0 } },
reportDate: { $dateToString: { date: new Date(), format: "%Y-%m-%d" } },
reportBy: "hellouser123",
reportNumber: { $literal: 1 }
}
)
#结果
{ "birth" : ISODate("1924-12-03T05:00:00Z"), "contribs" : [ "Fortran", "ALGOL", "Backus-Naur Form", "FP" ], "name" : "John Backus", "awards" : 4, "reportDate" : "2020-06-05", "reportBy" : "hellouser123", "reportNumber" : 1 }
{ "birth" : ISODate("1927-09-04T04:00:00Z"), "contribs" : [ "Lisp", "Artificial Intelligence", "ALGOL" ], "name" : "John McCarthy", "awards" : 3, "reportDate" : "2020-06-05", "reportBy" : "hellouser123", "reportNumber" : 1 }
{ "birth" : ISODate("1906-12-09T05:00:00Z"), "contribs" : [ "UNIVAC", "compiler", "FLOW-MATIC", "COBOL" ], "name" : "Grace Hopper", "awards" : 4, "reportDate" : "2020-06-05", "reportBy" : "hellouser123", "reportNumber" : 1 }
{ "birth" : ISODate("1926-08-27T04:00:00Z"), "contribs" : [ "OOP", "Simula" ], "name" : "Kristen Nygaard", "awards" : 3, "reportDate" : "2020-06-05", "reportBy" : "hellouser123", "reportNumber" : 1 }
{ "birth" : ISODate("1931-10-12T04:00:00Z"), "contribs" : [ "OOP", "Simula" ], "name" : "Ole-Johan Dahl", "awards" : 3, "reportDate" : "2020-06-05", "reportBy" : "hellouser123", "reportNumber" : 1 }
{ "birth" : ISODate("1956-01-31T05:00:00Z"), "contribs" : [ "Python" ], "name" : "Guido van Rossum", "awards" : 2, "reportDate" : "2020-06-05", "reportBy" : "hellouser123", "reportNumber" : 1 }
{ "birth" : ISODate("1941-09-09T04:00:00Z"), "contribs" : [ "UNIX", "C" ], "name" : "Dennis Ritchie", "awards" : 3, "reportDate" : "2020-06-05", "reportBy" : "hellouser123", "reportNumber" : 1 }
{ "birth" : ISODate("1965-04-14T04:00:00Z"), "contribs" : [ "Ruby" ], "name" : "Matz Matsumoto", "awards" : 1, "reportDate" : "2020-06-05", "reportBy" : "hellouser123", "reportNumber" : 1 }
{ "birth" : ISODate("1955-05-19T04:00:00Z"), "contribs" : [ "Java" ], "name" : "James Gosling", "awards" : 2, "reportDate" : "2020-06-05", "reportBy" : "hellouser123", "reportNumber" : 1 }
{ "contribs" : [ "Scala" ], "name" : "Martin Odersky", "awards" : 0, "reportDate" : "2020-06-05", "reportBy" : "hellouser123", "reportNumber" : 1 }
###7 排序
#name升序排序
db.bios.find().sort( { name: 1 } )
# 限制结果集中的文档数量。
db.bios.find().limit( 5 )
#控制结果集的起始点,跳过前5条
db.bios.find().skip( 5 )
# 联合使用
db.bios.find().sort( { name: 1 } ).limit( 5 )
db.bios.find().limit( 5 ).sort( { name: 1 } )
# skip() 和 limit() 联合使用 可分页查询
db.bios.find().skip( 5 ).limit(5)
2 db.collection.findOne(query, projection)
返回一个文档,该文档满足指定查询条件。如果多个文档满足条件,该方法将根据自然顺序返回第一个文档,即根据文档在磁盘上的顺序。在限定容量的集合中,自然顺序与插入顺序相同。如果没有文档满足查询,该方法将返回null
db.collection.findOne(query, projection)
参考 find()
3 db.collection.findAndModify(document)
修改并返回单个文档。默认情况下,返回的文档不包括对更新所做的修改。若要返回带有对更新所做修改的文档,请使用new选项。
3.1 语法
db.collection.findAndModify({
query: <document>,
sort: <document>,
remove: <boolean>,
update: <document or aggregation pipeline>, // Changed in MongoDB 4.2
new: <boolean>,
fields: <document>,
upsert: <boolean>,
bypassDocumentValidation: <boolean>,
writeConcern: <document>,
collation: <document>,
arrayFilters: [ <filterdocument1>, ... ]
});
4 db.collection.findOneAndDelete( filter, options )
根据筛选器和排序条件删除单个文档,返回已删除的文档
3.1 语法
db.collection.findOneAndDelete(
<filter>,
{
projection: <document>,
sort: <document>,
maxTimeMS: <number>,
collation: <document>
}
)
5 db.collection.findOneAndReplace( filter, replacement, options )
根据指定的筛选器替换单个文档,返回原始文档,如果returnNewDocument: true,则返回替换文档
5.1 语法
db.collection.findOneAndReplace(
<filter>,
<replacement>,
{
projection: <document>,
sort: <document>,
maxTimeMS: <number>,
upsert: <boolean>,
returnNewDocument: <boolean>,
collation: <document>
}
)
6 db.collection.findOneAndUpdate( filter, update, options )
根据筛选器和排序条件更新单个文档,在更新之前返回原始文档,如果returnNewDocument为true,返回更新后的文档
3.1 语法
db.collection.findOneAndUpdate(
<filter>,
<update document or aggregation pipeline>, // Changed in MongoDB 4.2
{
projection: <document>,
sort: <document>,
maxTimeMS: <number>,
upsert: <boolean>,
returnNewDocument: <boolean>,
collation: <document>,
arrayFilters: [ <filterdocument1>, ... ]
}
)
官网详情:
https://docs.mongodb.com/manual/reference/method/db.collection.find/https://docs.mongodb.com/manual/reference/method/db.collection.findOne/https://docs.mongodb.com/manual/reference/method/db.collection.findAndModify/https://docs.mongodb.com/manual/reference/method/db.collection.findOneAndDelete/https://docs.mongodb.com/manual/reference/method/db.collection.findOneAndReplace/https://docs.mongodb.com/manual/reference/method/db.collection.findOneAndUpdate/
操作符:https://docs.mongodb.com/manual/reference/operator/ 查询操作符: https://docs.mongodb.com/manual/reference/operator/query/