mongodb 查詢文件使用 find() 方法。
find() 方法以非結構化的方式來顯示所有文件。
mongodb 查詢資料的語法格式如下:
如果你需要以易讀的方式來讀取資料,可以使用 pretty() 方法,語法格式如下:db
.collection
.find
(query
,projection
)
.collection
.find
(query
,projection
)
pretty() 方法以格式化的方式來顯示所有文件。>db.
col.
find
().pretty
()
db.col
.find
().pretty
()
以下例項我們查詢了集合 col 中的資料:
除了 find() 方法之外,還有乙個 findone() 方法,它只返回乙個文件。>db.
col.
find
().pretty
()
db.col
.find
().pretty
()
如果你熟悉常規的 sql 資料,通過下表可以更好的理解 mongodb 的條件語句查詢:
操作格式
範例rdbms中的類似語句
等於
db.col.find().pretty()
where by = '菜鳥教程'
小於}
db.col.find(}).pretty()
where likes < 50
小於或等於
}
db.col.find(}).pretty()
where likes <= 50
大於}
db.col.find(}).pretty()
where likes > 50
大於或等於
}
db.col.find(}).pretty()
where likes >= 50
不等於}
db.col.find(}).pretty()
where likes != 50
mongodb 的 find() 方法可以傳入多個鍵(key),每個鍵(key)以逗號隔開,即常規 sql 的 and 條件。
語法格式如下:
以下例項通過 by 和 title 鍵來查詢菜鳥教程中mongodb 教程的資料>db.
col.
find
().pretty
()
db.col
.find
().pretty
()
以上例項中類似於 where 語句:where by='菜鳥教程' and title='mongodb 教程'>db.
col.
find
().pretty
()
db.col
.find
().pretty
()
mongodb or 條件語句使用了關鍵字$or,語法格式如下:
以下例項中,我們演示了查詢鍵by值為 菜鳥教程 或鍵title值為mongodb 教程的文件。>db.
col.
find(,
]}).pretty
()
db.col
.find(,
]}).pretty
()
以下例項演示了 and 和 or 聯合使用,類似常規 sql 語句為:'where likes>50 and (by = '菜鳥教程' or title = 'mongodb 教程')'>db.
col.
find
(,]}).
pretty
()>
db
.col
.find
(,]}).
pretty
()>
mongodb 刪除文件>db.
col.
find
(,$or
:[,]}).
pretty
()
db.col
.find
(,$or
:[,]}).
pretty
()
mongodb 條件操作符
筆記列表
dislido
dis***o@foxmail.com
補充一下 projection 引數的使用方法
若不指定 projection,則預設返回所有鍵,指定 projection 格式如下,有兩種模式db
.collection
.find
(query
,projection
)
.collection
.find
(query
,projection
)
_id 鍵預設返回,需要主動指定 _id:0 才會隱藏db
.collection
.find
(query,)
// inclusion模式 指定返回的鍵,不返回其他鍵db.
collection
.find
(query,)
// exclusion模式 指定不返回的鍵,返回其他鍵
.
collection
.find
(query,)
// inclusion模式 指定返回的鍵,不返回其他鍵db.
collection
.find
(query,)
// exclusion模式 指定不返回的鍵,返回其他鍵
兩種模式不可混用(因為這樣的話無法推斷其他鍵是否應返回)
只能全1或全0,除了在inclusion模式時可以指定_id為0db
.collection
.find
(query,)
// 錯誤
.
collection
.find
(query,)
// 錯誤
db
.collection
.find
(query,)
// 正確
.
collection
.find
(query,)
// 正確
Mongodb查詢文件
mongodb查詢文件 db.blog.find 檢視集合下的所有文件 db.blog.find limit 50 可以限制查詢文件的數量 db.blog.find limit 1 db.blog.find pretty 格式化查詢文件加上 pretty id objectid 5438dd3fa7...
MongoDB 查詢文件
mongodb 查詢資料 db.collection.find query,projection 易讀的方式來讀取資料,可以使用 pretty 方法 db.col.find pretty 通過 by 和 title 鍵來查詢 db.col.find pretty 類似於 where 語句 where...
mongoDB 文件查詢
在關係型資料庫中,可以實現基於表上各種各樣的查詢,以及通過投影來返回指定的列。對於nosql mongodb而言,所有能夠在單錶上完成的查詢,在mongodb中也可以完全勝任。除此之外,由於mongodb支援基於文件巢狀以及陣列,因此mongodb也可以實現基於巢狀文件和陣列的查詢。具體見下文描述。...