当前位置: 首页 > article >正文

MongoDB实践

MongoDB 是什么?— MongoDB 手册 v8.0

现在有一个名为city的集合,里面的结构如下图

一、增删改查操作

1.查询find
db.getCollection("city").find({})

db.city.find({
   
})

db.city.find({
    city:"广州"
});

db.city.find({
    city_id:17,
    city="shangh"
})
2.插入insert
db.city.insertOne({
    "city_id":8 , "city": "重庆"
})

db.getCollection("city").insertMany([
    { "id": 1, "city": "北京" },
    { "id": 2, "city": "上海" },
    { "id": 3, "city": "杭州" }
])

db.city.insertMany([
{
    city_id: 16,
    city: "宁波",
    population: 1999,
    is_deleted: 0
},
{
    city_id: 15,
    city: "西安",
    population: 1880,
    is_deleted: 0
},
])
3.更新update
//更新一条
db.city.update(
    { id: 4 },
    { $set: { city: "南京" } }
)
//更新多条
db.city.updateMany({},{$set:{
    " is_deleted":2
}});
//更新多条
const cities = ["长沙", "重庆", "武汉"];
const city_ids = ["17", "18", "19"];
const updates = cities.map((city, index) => ({
    updateOne: {
        filter: { city: city },
        update: { $set: { city_id: city_ids[index] } }
    }
}));
db.city.bulkWrite(updates, { ordered: false });  // 使用 bulkWrite 执行所有更新操作
4.删除remove
db.getCollection("city").remove(
    { id: 5 }
)

db.city.remove({city:"西安"})
二、操作符
1.比较查询
//eq
db.city.find({city:{$eq:"上海"}})

//gt
db.city.find({city_id:{$gt:3}})

//lt
db.city.find({ city_id: { $lt: 3 } })

//ne
db.city.find({ city_id: { $ne: 3 } })

//in
db.city.find({city:{$in:["上海","北京"]}})
db.city.updateMany(
    { city: { $in: ["上海", "北京"] } },
    { $set: { population: 3006 } }
)
2.逻辑查询
//and
//查询city不为上海且city_id在[2,3]里的
db.city.find(
{
    $and:[
      {  city:{$ne:"上海"}},
      {  city_id:{$in:[2,3]}}
    ]
})

//not
db.city.find({ city: { $not:{$in: ["上海", "北京"] }} })

//nor
db.city.find(
{
    $nor:[
      {  city:{$ne:"苏州"}},
      {  city_id:{$in:[2,9]}}
    ]
}
)

//or
db.city.find(
{
    $or:[
      {  city:{$ne:"苏州"}},
      {  city_id:{$in:[2,9]}}
    ]
}
)
3.元素查询
//exists
db.city.find({population:{$exists:false}})
db.city.find({population:{$exists:true}})

//type
db.city.find({city_id:{$type:"string"}})


http://www.kler.cn/a/504521.html

相关文章:

  • 【多模态LLM】LLaVA系列算法架构演进:LLaVA(1.0->1.5->Next(1.6)->NeXT(Video))
  • 7 分布式定时任务调度框架
  • 网络安全学习81天(记录)
  • Golang笔记——协程同步
  • 朴素贝叶斯分类器
  • <C++学习>C++ Boost 输入与输出教程
  • Java学习,集合遍历
  • SOME/IP协议详解 基础解读 涵盖SOME/IP协议解析 SOME/IP通讯机制 协议特点 错误处理机制
  • 人工智能实验(四)-A*算法求解迷宫寻路问题实验
  • Vue.js组件开发-使用地图绘制轨迹
  • 互联网架构困境:TCP/IP 拥塞难题与地址对称性
  • 九 RK3568 android11 MPU6500
  • what?ngify 比 axios 更好用,更强大?
  • mysql 查询语句的执行流程
  • 【Java】设计模式——代理模式
  • 【记录】篡改猴插件下载网页m3u8视频
  • 如何监控 Elasticsearch 集群健康状态并实现邮件自动预警?
  • R 语言科研绘图 --- 折线图-汇总
  • 代码随想录day03
  • 信息时代的消费者行为变迁与应对策略:基于链动2+1模式、AI智能名片及S2B2C商城小程序的分析