使用 find 搜索數組
find 支持對數組中的元素進行搜索。假設有一個文檔:
db.fruit.insert([
{ "name" : "Apple", color: ["red", "green" ] },
{ "name" : "Mango", color: ["yellow", "green"] }
])
那麼:
> db.fruit.find({color: "red"})
{ "_id" : ObjectId("5ea556f77cb2758a7f0a942f"), "name" : "Apple", "color" : [ "red", "green" ] }
> db.fruit.find({color: "green"})
{ "_id" : ObjectId("5ea556f77cb2758a7f0a942f"), "name" : "Apple", "color" : [ "red", "green" ] }
{ "_id" : ObjectId("5ea556f77cb2758a7f0a9430"), "name" : "Mango", "color" : [ "yellow", "green" ] }
> db.fruit.find({$or: [{color: "red"}, {color: "yellow"}]} )
{ "_id" : ObjectId("5ea556f77cb2758a7f0a942f"), "name" : "Apple", "color" : [ "red", "green" ] }
{ "_id" : ObjectId("5ea556f77cb2758a7f0a9430"), "name" : "Mango", "color" : [ "yellow", "green" ] }
使用 find 搜索數組中的對象
考慮以下文檔,
db.movies.insertOne(
{"title": "Raiders of the Lost Ark",
"filming_locations":
[{"city": "Los Angeles", "state": "CA", "country": "USA"},
{"city": "Rome", "state": "Lazio", "country": "Italy"},
{"city": "Florence", "state": "SC", "country": "USA"}]
}
)
// 查找城市是 Rome 的記錄
db.movies.find({"filming_locations.city": "Rome"})
// 在數組中搜索子對象的多個字段時,如果使用 $elemMatch,它表示必須是同一個 子對象滿足多個條件。考慮以下兩個查詢:
db.getCollection('movies').find({ "filming_locations": { $elemMatch:{"city":"Rome", "country": "USA"} } })
db.getCollection('movies').find({ "filming_locations.city": "Rome", "filming_locations.country": "USA" })
控制 find 返回的字段
- find 可以指定只返回指定的字段;
- _id字段必須明確指明不返回,否則默認返回;
- 在 MongoDB 中我們稱這爲投影(projection);
- db.movies.find({“category”: “action”},{"_id":0, title:1})
使用 remove 刪除文檔
- remove 命令需要配合查詢條件使用;
- 匹配查詢條件的的文檔會被刪除;
- 指定一個空文檔條件會刪除所有文檔;
- 以下示例:
- db.testcol.remove( { a : 1 } ) // 刪除a 等於1的記錄
- db.testcol.remove( { a : { $lt : 5 } } ) // 刪除a 小於5的記錄
- db.testcol.remove( { } ) // 刪除所有記錄
- db.testcol.remove() // 報錯
使用 update 來更新文檔
- Update 操作執行格式:db.<集合>.update(<查詢條件>, <更新字段>)
- 以以下數據爲例:
- db.fruit.insertMany([ {name: “apple”}, {name: “pear”}, {name: “orange”}])
- 查詢 name 爲 apple 的記錄, 將找到記錄的 from 設置爲 China
- db.fruit.updateOne({name: “apple”}, {$set: {from: “China”}})
- 使用 updateOne 表示無論條件匹配多少條記錄,始終只更新第一條;
- 使用 updateMany 表示條件匹配多少條就更新多少條;
- updateOne/updateMany 方法要求更新條件部分必須具有以下之一,否則將報錯: •
$set/$unset
$push/$pushAll/$pop
$pull/$pullAll
$addToSet