使用find查询文档
find
find是mongodb的查询操作,相当于sql中的select
返回值为游标,特别需要注意的是,如果在使用游标的时候,没有遍历完游标,最好使用close方法关闭游标,这样可以减少资源
示例
db.movies.find( { "year" : 1975 } ) // 单条件查询,查询year为1975的所有数据
db.movies.find( { "year" : 1989, "title" : "Batman" } ) // 多条件 and 查询
db.movies.find( { $and : [ {"title" : "Batman"}, { "category" : "action" }] } ) // and 的另一种形式
db.movies.find( { $or: [{"year" : 1989}, {"title" : "Batman"}] } ) // 多条件 or 查询
db.movies.find( { "title" : /^B/} ) // 按正则表达式查找
查询条件对照表
# a=1
{a:1}
# a<>1
{a:{$ne:1}} # $ne为不等于
# a>1
{a:{$gt:1}} # $gt大于
# a>=1
{a:{$gte:1}} # $gte 大于等于
# a<1
{a:{$lt:1}} # $lt 小于
# a<=1
{a:{$lte:1}} # $lte 小于等于
# a=1 and b=1
{$and:[{a:1},{b:1}]} # 多条件$and的用法
# a=1 or b=1
{$or:[{a:1},{b:1}]} # $or 多条件或
# a is Null
{a:{$exists:false}} # $exists 判断是否存在
# a in [1,2,3]
{a:{$in:[1,2,3]}} # $in 的用法
子文档查询
# 数据:
{
"name": "apple",
"from": {
country: "China",
province: "Guangdon"
}
}
# 查询:
db.fruit.find( { "from" : {country: "China"} } ) # 查询from字段下country字段为China的数据
数组查询
# 数据
{
"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" }
]
}
# 查询
db.movies.find({"filming_locations.city": "Rome"}) # 查询filming_locations中city为Rome的数据
# 若多条件
db.getCollection('movies').find({
"filming_locations.city": "Rome",
"filming_locations.country": "USA"
})
控制find的返回字段
db.movies.find({"category": "action"},{"_id":0, title:1}) # 只返回title,不返回_id
使用update更新文档
update操作格式:db.collection.update(<查询条件>,<更新字段>)
更新文档
db.fruit.updateOne({"name": "apple"}, {$set:{"from": "China"}})
更新数组
$push 增加一个对象到数组底部
$pushAll: 增加多个对象到数组底部
$pop: 从数组底部删除一个对象
$pull: 如果匹配指定的值,从数组中删除相应的对象
$pullAll: 如果匹配任意的值,从数据中删除相应的对象
$addToSet: 如果不存在则增加一个值到数组