使用 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