MongoDB 高级CRUD操作

此为mongodb CRUD命令操作,由简到高级查询

基础部分

1.插入操作(以User表为例)

db.adminUser.insertOne({ 
    "openId": "admin_b075df20d85711e98ba819498dwf0854",
    "jurisdiction": "SSS",
    "email": "15908619975@163.com",
    "password": "eyJhbGciOiJIUzI1NiJ9.Y2hlbmJpZGExMjM.MMYEzVwo8ogN6QEptMDLQXGenhy1rUQJZLHK-FgLAK0",
    "username": "Nick_Chen",
    "jobNumber": "ws3213",
    "Avatat": "https://www.mychen.vip/static/imgs/avatar.jpg"
})

2.删除操作(deleteOne:删除一条,deleteMany:满足条件全部删除)

db.adminUser.deleteOne({"openId": "admin_b075df20d85711e98ba819498dwf0854","email": "15908619975@163.com"})

3.修改(updateOne:修改一条,updateMany:满足条件全部修改)

db.adminUser.updateOne(

{"openId": "admin_b075df20d85711e98ba819498dwf0854","email": "15908619975@163.com"},

{$set:{"username":"Hunter"}}

)

**************************

//例如需要在原有数据上加1 

db.adminUser.updateOne(

{"openId": "admin_b075df20d85711e98ba819498dwf0854","email": "15908619975@163.com"},

{$inc:{"Sum": +1 }} // +1 或 -1

)

************更新array数据类型*************

//添加数组元素

db.adminUser.updateOne(

{"openId": "admin_b075df20d85711e98ba819498dwf0854","email": "15908619975@163.com"},

{ $push:{ conent:{ id: 1, name: "nick" } } }

)

//删除数组中的元素

db.adminUser.updateOne(

{"openId": "admin_b075df20d85711e98ba819498dwf0854","email": "15908619975@163.com"},

{ $pull:{ conent:{ id: 1, name: "nick" } } }

)

************修改数组中object对象*************

//versionInfo.$.type  $符号类似于数组的角标。会查找符合条件的下标object对象进行修改

db.commodity.updateMany({

"productId":"148020190801154510","versionInfo.type":{$all:["原味"]},"versionInfo.versions":{$all:["5kg"]}},

{$set:{"versionInfo.$.type":"原味","versionInfo.$.versions":"5kg","versionInfo.$.price":"44","versionInfo.$.inventory":88}},{"multi":true})

 

4.查询

db.adminUser.find()

db.adminUser.find({"openId": "admin_b075df20d85711e98ba819498dwf0854","email": "15908619975@163.com"})

//分页查询

db.adminUser.find().skip(0).limit(10)

******************************

$in $all 多用于 Array字段。例如【'外卖','预约','堂食'】

//同字段多条件,任何一个条件满足即查

db.adminUser.find({"type":$in:["预约","堂食"]})

//同字段多条件,必须满足条件

db.adminUser.find({"type":$all:["外卖"]})

高级部分

1.联表查询

字段类型数据描述
productIdString126220200708103609商品ID
openIdStringadmin_b075df20d85711e98ba819498dwf0854商品所属商店
productNameStringMongodb入门商品名称
productTypeStringBook商品类型
priceNumber99价格
findStatusNumber1过审状态
createTimeDate2020-07-18T10:13:14.000Z创建时间
updateTimeDate2020-07-18T10:30:14.000Z过审时间,修改时间
db.adminUser.aggregate([

   {
        $lookup:
        {
            from: "Product",
            localField: "openId",
            foreignField: "openId",
            as: 'subsetDetails'
        }
    },

   //查询条件

   { $match: { "subsetDetails.productName": { $all: ['Mongodb入门'] } } },

   //排序
   {
        $sort: { createTime:1}
   }

])

2.统计查询(以订单表为例,统计交易总数)

字段类型数据描述
orderIdString202006121458101694订单ID
userOpenIdStringclient_b722b1a07eebdw717cbb858ae1d743c0用户ID
sellerOpenIdStringadmin_b075df20d85711e98ba819498dwf0854卖家ID
productIdString126220200708103609商品ID
coupon

Boolean

false是否使用优惠卷
priceNumber99商品实际金额
payment_amountNumber99支付金额
payment_statusNumber1支付状态
payment_typeStringalipay支付平台
create_TimeDate2020-08-18T10:30:14.000Z订单生成时间
db.orders.aggregate(

{//过滤条件
        $match:{
            "sellerOpenId":"admin_b075df20d85711e98ba819498dwf0854",
        }
},

{

     $group:{

          _id:'$id',

          payment_amount:{$sum:'$payment_amount'},

     }

})

索引部分

1.设置普通检索索引(普通索引不作过多描述)

db.adminUser.createIndex({ "openId": 1, "email": 1})

2.添加数据过期索引(根据Date数据字段,达到时间会自动删除此条数据,以购物优惠卷为例)

字段类型数据源描述
couponIdString177720200713155824优惠卷ID
ShopNameString陈小胖零食店所属商店
monetaryUnitString¥结算机制
couponTypeStringBook优惠类型(以书籍为例)
startingTimeDate2020-07-13T15:57:52.000Z优惠卷开始时间
endTimeDate2021-09-30T07:57:52.000Z优惠卷结束时间(自动删除)
priceFullNumber50满足金额
priceSubtractNumber10优惠金额
createTimeDate2020-07-13T15:57:52.000Z创建日期
//设置数据过期时间 expireAfterSeconds 参数为0 代表到期直接删除

db.coupon.createIndex({ "endTime": 1 }, { expireAfterSeconds: 0 })

//expireAfterSeconds 参数为60代表延迟60秒后参数

db.auth_session.createIndex({ "endTime": 1 }, { expireAfterSeconds: 60 })

高级索引

1.地图索引(注意:索引字段必须为数组,例:"storeLocation": [114.005388, 22.704099 ])以商铺地址为例

字段类型数据描述
openIdStringadmin_b075df20d85711e98ba819498dwf0854ID
shopNameString陈小胖零食店商店名称
storeCityArray[ "中国", "广东省",  "深圳市" ]所属城市
storeAddressString龙华新区商店地址
storeLocationArray[114.005388, 22.704099 ]商店所属经纬度
findStatusNumber1审核状态
createTimeDate2020-07-08T10:13:14.000Z创建时间
//设置索引

db.wav_users.createIndex({"storeLocation" : "2d"})
db.wav_users.createIndex({"storeLocation" : "2dsphere"});
//查询

db.store.aggregate([
      {
        $geoNear:
        {
            near: { type: "Point", coordinates: [113.9989793301, 22.6981093823] },
            key: "storeLocation",
            distanceField: "dist", //两点间的距离  以米为单位,查询结果会有dist字段内容为2个经纬度的距离
            //query: { },//筛选条件 如 {findStatus:1}
        }
    }
])

2.地图索引高级查询(有联表查询操作引用上面的product表)

db.store.aggregate([
      {
        $geoNear:
        {
            near: { type: "Point", coordinates: [113.9989793301, 22.6981093823] },
            key: "storeLocation",
            distanceField: "dist", //两点间的距离  以米为单位
            // query: { },//筛选store表条件
        }
    },
    {//联表操作
        $lookup:
        {
            from: "Product",
            localField: "openId",
            foreignField: "openId",
            as: 'subsetDetails'
        }
    },
    {
        "$project": {//指定输出字段
            "openId": "$openId",
            "shopName": "$shopName",
            "storeCity": "$storeCity",
            "storeAddress": "$storeAddress",
            "storeLocation": "$storeLocation",
            "findStatus": "$findStatus",
            "createTime": "$createTime",
            "dist": "$dist",
            "subsetDetails": {
                $filter: { //过滤掉未审核的团购,此处findStatus指向product表中的商品审核字段
                    input: "$subsetDetails",
                    as: "item",

                    //cond 可以多条件 例: { $eq: ["$$item.findStatus", 1],$eq: ["$$item.productName", 'Mongodb入门'] }
                    cond: { $eq: ["$$item.findStatus", 1] }
                }
            }
        }
    },

    //条件过滤。
    { $match: { } },
    {
        $sort: { "dist": 1 }
    }
])

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值