mongo 课程笔记之基本操作2

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

使用 update 来更新数组

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值