MongoDB的查询操作与更新操作

使用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: 如果不存在则增加一个值到数组
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值