首页 > 其他分享 >简单查询

简单查询

时间:2023-11-10 09:44:44浏览次数:32  
标签:city name ObjectId country db NumberDecimal 查询 简单

计划

今天要学习《06 MongoDB基本操作》

Mongo的连接地址格式

mongodb://username:password@host[:port]/database?<options>

基本操作

以下都在shell环境下

查看当前数据库

> db
mock

切换数据库

> use test

查看当前表

> show collections
> show tables

插入一条记录

> db.fruit.insertOne({name: "apple"})
{
        "acknowledged" : true,
        "insertedId" : ObjectId("5dfcae3eebbe93035d7c6b55")
}

插入多条记录

> db.fruit.insertMany([
... {name: "apple"},
... {name: "pear"},
... {name: "orage"}
... ])
{
        "acknowledged" : true,
        "insertedIds" : [
                ObjectId("5dfcb07debbe93035d7c6b56"),
                ObjectId("5dfcb07debbe93035d7c6b57"),
                ObjectId("5dfcb07debbe93035d7c6b58")
        ]
}

检索记录

相当于 select 返回的是游标

> db.fruit.find()
{ "_id" : ObjectId("5dfcae3eebbe93035d7c6b55"), "name" : "apple" }
{ "_id" : ObjectId("5dfcb07debbe93035d7c6b56"), "name" : "apple" }
{ "_id" : ObjectId("5dfcb07debbe93035d7c6b57"), "name" : "pear" }
{ "_id" : ObjectId("5dfcb07debbe93035d7c6b58"), "name" : "orage" }

单条件查询(一个条件)

> db.orders.find({"name":"Destinee Schneider"})
{
    "_id": ObjectId("5dbe7a545368f69de2b4d36e"),
    "street": "493 Hilll Curve",
    "city": "Champlinberg",
    "state": "Texas",
    "country": "Malaysia",
    "zip": "24344-1715",
    "phone": "425.956.7743 x4621",
    "name": "Destinee Schneider",
    "userId": 3573,
    "orderDate": ISODate("2019-03-26T03:20:08.805Z"),
    "status": "created",
    "shippingFee": NumberDecimal("8.00"),
    "orderLines": [{
        "product": "Refined Fresh Tuna",
        "sku": "2057",
        "qty": 25,
        "price": NumberDecimal("56.00"),
        "cost": NumberDecimal("46.48")
    }, {
        "product": "Refined Concrete Ball",
        "sku": "1738",
        "qty": 61,
        "price": NumberDecimal("47.00"),
        "cost": NumberDecimal("47")
    }, {
        "product": "Rustic Granite Towels",
        "sku": "500",
        "qty": 62,
        "price": NumberDecimal("74.00"),
        "cost": NumberDecimal("62.16")
    }, {
        "product": "Refined Rubber Salad",
        "sku": "1400",
        "qty": 73,
        "price": NumberDecimal("93.00"),
        "cost": NumberDecimal("87.42")
    }, {
        "product": "Intelligent Wooden Towels",
        "sku": "5674",
        "qty": 72,
        "price": NumberDecimal("84.00"),
        "cost": NumberDecimal("68.88")
    }, {
        "product": "Refined Steel Bacon",
        "sku": "5009",
        "qty": 8,
        "price": NumberDecimal("53.00"),
        "cost": NumberDecimal("50.35")
    }],
    "total": NumberDecimal("407")
}

多条件 and 查询(1)

> db.orders.find({"country":"Italy","city":"North Elliot"})
{
    "_id": ObjectId("5dbe7a5b50fc769de3e1a0f8"),
    "street": "5769 Von Trail",
    "city": "North Elliot",
    "state": "South Dakota",
    "country": "Italy",
    "zip": "93708-8445",
    "phone": "1-390-726-3544",
    "name": "Alexys Swift",
    "userId": 9628,
    "orderDate": ISODate("2019-07-25T07:21:14.661Z"),
    "status": "completed",
    "shippingFee": NumberDecimal("10.00"),
    "orderLines": [{
        "product": "Refined Plastic Computer",
        "sku": "5065",
        "qty": 50,
        "price": NumberDecimal("82.00"),
        "cost": NumberDecimal("71.34")
    }, {
        "product": "Generic Granite Gloves",
        "sku": "4352",
        "qty": 10,
        "price": NumberDecimal("37.00"),
        "cost": NumberDecimal("32.56")
    }, {
        "product": "Practical Rubber Chicken",
        "sku": "2035",
        "qty": 29,
        "price": NumberDecimal("84.00"),
        "cost": NumberDecimal("68.04")
    }, {
        "product": "Handcrafted Fresh Bike",
        "sku": "2276",
        "qty": 51,
        "price": NumberDecimal("77.00"),
        "cost": NumberDecimal("64.68")
    }, {
        "product": "Sleek Cotton Car",
        "sku": "5257",
        "qty": 6,
        "price": NumberDecimal("94.00"),
        "cost": NumberDecimal("79.9")
    }, {
        "product": "Practical Fresh Mouse",
        "sku": "9593",
        "qty": 67,
        "price": NumberDecimal("98.00"),
        "cost": NumberDecimal("96.04")
    }, {
        "product": "Incredible Plastic Ball",
        "sku": "7804",
        "qty": 22,
        "price": NumberDecimal("45.00"),
        "cost": NumberDecimal("39.15")
    }, {
        "product": "Refined Plastic Bike",
        "sku": "9804",
        "qty": 27,
        "price": NumberDecimal("22.00"),
        "cost": NumberDecimal("18.92")
    }, {
        "product": "Handcrafted Concrete Shoes",
        "sku": "1473",
        "qty": 1,
        "price": NumberDecimal("49.00"),
        "cost": NumberDecimal("44.1")
    }],
    "total": NumberDecimal("588")
}

多条件 and 查询(2)

> db.orders.find({$and: [{"country":"Italy"},{"city":"North Elliot"}]})

多条件 or 查询

> db.orders.find({$or:[{"country":"Italy"},{"city":"North Elliot"}]})

正则表达式查询

> db.orders.find({"country": /^I/}) 

查询条件

SQLMQL
a=1 {a: 1}
a<>1 {a: {$ne: 1}}
a>1 {a: {$gt: 1}}
a<1 {a: {$lt: 1}}
a>=1 {a: {$gte: 1}}
a<=1 {a: {$lte: 1}}
a=1 and b=1 {a:1,b:1} 或 {$and: [{a:1},{b:1}]}
a=1 or b=1 {$or:[{a:1},{b:1}]}
a=null {a: {$exists:false}}
a in (1,2,3) {a: {$in:[1,2,3]}}
a not in(1,2,3) {a: {$nin:[1,2,3]}}

搜索子文档

> db.fruit.insertOne({
    name: "apple",
    from:{
        country: "China",
        province: "Guangdon"
    }
})

要查询China

> db.fruit.find({"from.country":"China"})
{ 
    "_id" : ObjectId("5dfcc154d432688fd475d7a4"), 
    "name" : "apple", 
    "from" : {
        "country" : "China", 
        "province" : "Guangdon"
    }
}

查询数组中的值

> db.fruit.insert([
    {
        "name":"Apple",
        "color":["red","green"]
    },
    {
        "name":"Mango",
        "color":["yellow","green"]
    }
])
方式1
> db.fruit.find({"color":"red"})
{ "_id" : ObjectId("5dfcc543f598f9f1c332185f"), "name" : "Apple", "color" : [ "red", "green" ] }
方式2
> db.fruit.find({$or: [{"color":"red"},{"color":"yellow"}]})
{ 
    "_id" : ObjectId("5dfcc2eed432688fd475d7a6"), 
    "name" : "Mango", 
    "color" : [
        "yellow", 
        "green"
    ]
},
{ 
    "_id" : ObjectId("5dfcc543f598f9f1c332185f"), 
    "name" : "Apple", 
    "color" : [
        "red", 
        "green"
    ]
}

查询数组中的对象

> 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"
        }
    ]
})
一个条件
> db.movies.find({
    "filming_locations.city": "Rome"
})
{ 
    "_id" : ObjectId("5dfcc850d432688fd475d7a7"), 
    "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_locaionts.country": "Italy"
})

应该这么写

> db.movies.find({
    "filming_locations": {
        $elemMatch: {
            "city":"Rome",
            "country": "Italy"
        }
    }
})

{ 
    "_id" : ObjectId("5dfcc850d432688fd475d7a7"), 
    "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"
        }
    ]
}

控制 find 返回的字段

  • 返回所有记录,但只要 title 字段,不要 _id 字段
> db.movies.find({},{"_id":0,"title":1})
{ 
    "title" : "Raiders of the Lost Ark"
}

对 find 返回的结果进行格式化

> db.movies.find().pretty()

要不然在SHELL下面是这样的

{ "_id" : ObjectId("5dfcc850d432688fd475d7a7"), "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" } ] }

加完变这样了

{
    "_id" : ObjectId("5dfcc850d432688fd475d7a7"),
    "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"
        }
    ]
}

删除文档

删除指定 _id 的记录
> db.fruit.remove({"_id" : ObjectId("5dfcc543f598f9f1c3321860")})
删除指定条件的文档
> db.fruit.remove({"color":"red"})
WriteResult({ "nRemoved" : 2 })
删除所有
> db.movies.remove({})
不给参数会报错
> db.movies.remove()

更新文档

只作用于集合中存在的文档

更新值

将下面的 name 是 apple 的改成 Apple

{ 
    "_id" : ObjectId("5dfcc154d432688fd475d7a4"), 
    "name" : "apple", 
    "from" : {
        "country" : "China", 
        "province" : "Guangdon"
    }
}
{ 
    "_id" : ObjectId("5dfcc2eed432688fd475d7a5"), 
    "name" : "Apple", 
    "color" : [
        "read", 
        "green"
    ]
}
{ 
    "_id" : ObjectId("5dfcc2eed432688fd475d7a6"), 
    "name" : "Mango", 
    "color" : [
        "yellow", 
        "green"
    ]
}
> db.fruit.update({"name": "apple"}, {$set: {"name": "Apple"}})
加个字段
> db.fruit.updateOne({"name":"Mango"},{$set: {"from":"China"}})
更新条件

updateOne 与 updateMany

条件作用
$push 添加一个对象到数组底部
$pushAll 添加多个对象到数组底部
$pop 从数组底部删除一个对象
$pull 如果满足指定条件,就从数组中删除对象
$pullAll 如果满足任意条件,就从数组中删除对象
$addToSet 如果不存在,就增加值到数组

删除集合 drop

删除了没办法恢复哈

> db.fruit.drop()

删除数据库 dropDatabase

 
> db.dropDatabase()

标签:city,name,ObjectId,country,db,NumberDecimal,查询,简单
From: https://www.cnblogs.com/lovezhr/p/17823400.html

相关文章

  • 高斯数据库HCNA之数据查询
    一、数据查询1、简单查询日常查询中,最常用的是通过FROM子句实现的查询语法格式使用方法:SELECT[,...]FROMtable_reference[,...]SELECT关键字之后和FROM子句之前出现的表达式称为SELECT项,SELECT项用于指定要查询的列,FROM指定要从哪个表中查询如果要查询所有列,可以在SE......
  • MySQL千万级数据库查询怎么提高查询效率
     查询效率慢的原因: 1:没有加索引或者索引失效  where条件使用如下语句会索引失效:null、!=、<>、or连接、in(非要使用,可用关键字exist替代)和notin、'%abc%';  使用参数:num=@num、表达式操作:wherenum/2=100、函数操作:wheresubstring(name,1,3)=‘abc’-name;   --e......
  • mybatis使用id集合查询数据
    dao层intdelUser(@Param("menuId")IntegermenuId,@Param("idList")List<String>idList);xml层<deleteid="delUser">deleteFROMuser_role_menuWHEREmenu_id=#{menuId}ANDuser_idNOTIN<f......
  • 一个简单的存储过程例子
    创建存储过程createorreplaceprocedurep_delete_dlljgas begin deletefromsys_dlljg;commit;end;创建制定执行计划(每周一22点55分执行一次)DECLAREiInteger;BEGINdbms_job.submit(i,'p_delete_dlljg;',sysdate,'TRUNC(next_day(sysdate,1))+(22*60+5......
  • Rust之cargo简单熟悉
    Rust之cargo简单熟悉还记得上一篇文章–《Rust简单开发环境搭建》中,helloworld的例子是用cargo来管理的,今天我们就来聊聊这个cargocargo是什么?为什么需要这个cargo?cargo是Rust的包管理器,Rust的包分为2种,一种是二进制可执行的包,一种是库的包,默认情况下就是第一种binary包在Rust里......
  • Rust简单开发环境搭建
    Rust简单开发环境搭建Rust简单开发环境搭建整个环境搭建默认在X86的Linux环境(Ubuntu)下进行环境搭建首先,要熟悉下Rust的几个基本东东:rustup:Rust版本管理器cargo:Rust包管理器rustc:Rust编译器安装使用官方推荐的rustup方式进行安装,使用下面的一条命令即可:SHELLcurl......
  • OpenHarmony基于HDF简单驱动开发实例
    OpenHarmony基于HDF简单驱动开发实例背景OpenHarmony-3.0-LTSqemu_small_system_demoliteos_aqemu添加配置device/qemu/arm_virt/liteos_a/hdf_config/device_info/device_info.hcsdevice_info新增:sample_host::host{hostName="sample_host";sample_device::devi......
  • 简单的C程序示例
        程序调整:程序的输出是否在屏幕上一闪而过?如果遇到这种情况,可以在程序中添加额外的代码,让窗口等待用户按下一个键后关闭。一种方法是,在程序的return语句前添加一行代码。  getchar();这行代码会让程序等待击键,窗口会在用户按下一个键后才关闭。    1、#inclu......
  • JAVA怎么画三角形,用一个简单通俗的例子
    在Java中,画三角形通常意味着在图形用户界面(GUI)上绘制一个三角形的图形,或者在控制台(命令行界面)上打印出三角形的形状。我会提供两种情况的简单示例: ###控制台三角形 如果我们要在控制台中打印一个三角形,我们可以使用循环来打印一系列的星号(`*`)字符。下面是一个简单的例子: ......
  • 从 SQL 查询优化技巧去看 h2 数据库查询原理 | 京东物流技术团队
    本文目标是:了解查询的核心原理,对比SQL查询优化技巧在h2database中的落地实现。前提:为了贴近实际应用,本文CodeInsight基于BTree存储引擎。数据查询核心原理数据库实现查询的原理:遍历表/索引,判断是否满足where筛选条件,添加到结果集。简单通用。对于选择表还是索引、如何遍历......