mongoDB 方法 -- 查找文檔 find()


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/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM