MongoDB CRUDBasicsoperation

MasterMongoDB 插入, query, update and deleteoperation core语法 and usingtechniques

CRUDoperationIntroduction

CRUD is datalibraryoperation basicfunctions, 代表creation(Create), 读取(Read), update(Update) and delete(Delete)四个operation. in MongoDBin, 这些operation for 应不同 method and 语法.

MongoDB CRUDoperation概览

operationclass型 MongoDBmethod describes
creation insertOne(), insertMany() 插入一个 or many 个documentation
读取 find(), findOne() querydocumentation
update updateOne(), updateMany(), replaceOne() update一个 or many 个documentation
delete deleteOne(), deleteMany() delete一个 or many 个documentation

提示: in MongoDB Shellin执行这些operation时, 需要先切换 to 目标datalibrary, usinguse database_namecommands.

插入operation

1. insertOne()method

用于插入单个documentation to collectionin.

// 插入单个documentation
use test

db.users.insertOne({
    "name": "张三",
    "age": 30,
    "email": "zhangsan@example.com",
    "address": {
        "street": "北京市海淀区in关村 big 街",
        "city": "北京"
    },
    "hobbies": ["读书", "旅游", "programming"],
    "createdAt": new Date()
})

// 插入operation 返回结果
{
    "acknowledged" : true,
    "insertedId" : ObjectId("5f8d0f9a9b2c3d4e5f6a7b8c")
}

2. insertMany()method

用于批量插入 many 个documentation to collectionin.

// 批量插入 many 个documentation
db.users.insertMany([
    {
        "name": "李四",
        "age": 25,
        "email": "lisi@example.com",
        "createdAt": new Date()
    },
    {
        "name": "王五",
        "age": 35,
        "email": "wangwu@example.com",
        "createdAt": new Date()
    },
    {
        "name": "赵六",
        "age": 28,
        "email": "zhaoliu@example.com",
        "createdAt": new Date()
    }
])

// 批量插入 返回结果
{
    "acknowledged" : true,
    "insertedIds" : [
        ObjectId("5f8d0f9a9b2c3d4e5f6a7b8d"),
        ObjectId("5f8d0f9a9b2c3d4e5f6a7b8e"),
        ObjectId("5f8d0f9a9b2c3d4e5f6a7b8f")
    ]
}

插入operation 选项

insertMany()methodsupport以 under 选项:

// 插入选项example
db.users.insertMany([
    { "name": "孙七", "age": 40 },
    { "name": "周八", "age": 45 }
], {
    "ordered": true,  //  is 否按顺序插入, 默认 for true
    "writeConcern": { "w": 1, "wtimeout": 1000 }
})

// ordered: true 时, such as果遇 to error会停止插入
// ordered: false 时, 会继续插入otherdocumentation

queryoperation

1. findOne()method

用于query并返回第一个匹配 documentation.

// query单个documentation
db.users.findOne({ "name": "张三" })

// 返回结果
{
    "_id" : ObjectId("5f8d0f9a9b2c3d4e5f6a7b8c"),
    "name" : "张三",
    "age" : 30,
    "email" : "zhangsan@example.com",
    "address" : {
        "street" : "北京市海淀区in关村 big 街",
        "city" : "北京"
    },
    "hobbies" : [ "读书", "旅游", "programming" ],
    "createdAt" : ISODate("2020-10-19T08:00:00Z")
}

2. find()method

用于query并返回所 has 匹配 documentation.

// query所 has documentation
db.users.find()

// 条件query
db.users.find({ "age": { "$gt": 30 } })  // query年龄 big 于30 user

// 投影query (指定返回字段) 
db.users.find(
    { "age": { "$gt": 25 } },
    { "name": 1, "age": 1, "email": 1, "_id": 0 }
)

// sortquery
db.users.find().sort({ "age": -1 })  // 按年龄降序sort

// 限制结果数量
db.users.find().limit(5)

// 跳过指定数量 结果
db.users.find().skip(5).limit(5)

commonqueryoperation符

operation符 describes example
$eq etc.于 { "age": { "$eq": 30 } }
$ne 不etc.于 { "age": { "$ne": 30 } }
$gt big 于 { "age": { "$gt": 30 } }
$gte big 于etc.于 { "age": { "$gte": 30 } }
$lt small 于 { "age": { "$lt": 30 } }
$lte small 于etc.于 { "age": { "$lte": 30 } }
$in in 指定arrayin { "age": { "$in": [25, 30, 35] } }
$nin 不 in 指定arrayin { "age": { "$nin": [25, 30, 35] } }

updateoperation

1. updateOne()method

用于update第一个匹配 documentation.

// update单个documentation
db.users.updateOne(
    { "name": "张三" },  // query条件
    {
        "$set": { "age": 31, "email": "zhangsan_new@example.com" },  // updateoperation
        "$currentDate": { "lastUpdated": true }  // update时间戳
    }
)

// updateoperation 返回结果
{
    "acknowledged" : true,
    "matchedCount" : 1,
    "modifiedCount" : 1
}

2. updateMany()method

用于update所 has 匹配 documentation.

// update many 个documentation
db.users.updateMany(
    { "age": { "$lt": 30 } },  // query条件
    {
        "$set": { "status": "young" },
        "$currentDate": { "lastUpdated": true }
    }
)

// updateoperation 返回结果
{
    "acknowledged" : true,
    "matchedCount" : 2,
    "modifiedCount" : 2
}

3. replaceOne()method

用于replace整个documentation (除了_id字段) .

// replacedocumentation
db.users.replaceOne(
    { "name": "张三" },  // query条件
    {
        "name": "张三",
        "age": 32,
        "email": "zhangsan@example.com",
        "address": {
            "street": "北京市朝阳区建国路",
            "city": "北京"
        },
        "hobbies": ["读书", "旅游", "programming", "摄影"],
        "createdAt": new Date()
    }
)

常用updateoperation符

operation符 describes example
$set 设置字段值 { "$set": { "age": 31 } }
$unset delete字段 { "$unset": { "age": "" } }
$inc 增加字段值 { "$inc": { "age": 1 } }
$mul 乘以指定值 { "$mul": { "price": 1.1 } }
$rename rename字段 { "$rename": { "oldField": "newField" } }
$push 向array添加元素 { "$push": { "hobbies": "摄影" } }
$pull from arraydelete元素 { "$pull": { "hobbies": "读书" } }
$addToSet 向array添加元素 (仅当不存 in 时) { "$addToSet": { "hobbies": "摄影" } }

deleteoperation

1. deleteOne()method

用于delete第一个匹配 documentation.

// delete单个documentation
db.users.deleteOne({ "name": "张三" })

// deleteoperation 返回结果
{
    "acknowledged" : true,
    "deletedCount" : 1
}

2. deleteMany()method

用于delete所 has 匹配 documentation.

// delete many 个documentation
db.users.deleteMany({ "age": { "$gt": 40 } })

// deleteoperation 返回结果
{
    "acknowledged" : true,
    "deletedCount" : 2
}

// deletecollectionin 所 has documentation
db.users.deleteMany({})

// delete整个collection (更 high 效) 
db.users.drop()

warning: deleteoperation is 不可逆 , 请谨慎using. in 执行deleteoperation before , 建议先forquery确认, or 考虑using软delete (标记字段) 替代物理delete.

实践case

case: usermanagementsystemCRUDoperation

implementation一个 simple usermanagementsystem, package含user creation, query, update and deleteoperation.

// 1. creationusercollection并插入testdata
use user_management

db.users.insertMany([
    {
        "username": "admin",
        "name": "management员",
        "email": "admin@example.com",
        "role": "admin",
        "status": "active",
        "createdAt": new Date()
    },
    {
        "username": "user1",
        "name": "user1",
        "email": "user1@example.com",
        "role": "user",
        "status": "active",
        "createdAt": new Date()
    },
    {
        "username": "user2",
        "name": "user2",
        "email": "user2@example.com",
        "role": "user",
        "status": "inactive",
        "createdAt": new Date()
    }
])

// 2. queryoperation
// query所 has 活跃user
db.users.find({ "status": "active" })

// querymanagement员user
db.users.find({ "role": "admin" })

// 3. updateoperation
// 激活user2
db.users.updateOne(
    { "username": "user2" },
    { "$set": { "status": "active" } }
)

//  for 所 has user添加lastLogin字段
db.users.updateMany(
    {},
    { "$set": { "lastLogin": null } }
)

// 4. deleteoperation
// delete指定user
db.users.deleteOne({ "username": "user2" })

// delete所 has 非活跃user
db.users.deleteMany({ "status": "inactive" })

互动练习

练习1: implementation产品managementCRUDoperation

creation一个产品collection, implementation以 under operation: 1. 插入3个产品documentation, package含name, price, category, stocketc.字段 2. query价格 big 于100 产品 3. update所 has 电子产品 价格, 增加10% 4. deletelibrary存 for 0 产品

referenceimplementation:

// 1. 插入产品data
use product_management

db.products.insertMany([
    {
        "name": "iPhone 12",
        "price": 6999,
        "category": "electronics",
        "stock": 50,
        "createdAt": new Date()
    },
    {
        "name": "MacBook Pro",
        "price": 12999,
        "category": "electronics",
        "stock": 30,
        "createdAt": new Date()
    },
    {
        "name": "AirPods Pro",
        "price": 1999,
        "category": "electronics",
        "stock": 0,
        "createdAt": new Date()
    }
])

// 2. query价格 big 于100 产品
db.products.find({ "price": { "$gt": 100 } })

// 3. update所 has 电子产品 价格, 增加10%
db.products.updateMany(
    { "category": "electronics" },
    { "$mul": { "price": 1.1 } }
)

// 4. deletelibrary存 for 0 产品
db.products.deleteMany({ "stock": 0 })

练习2: usingupdateoperation符

给定以 under userdocumentation:
{"_id": ObjectId(...), "name": "张三", "age": 30, "hobbies": ["读书", "旅游"], "address": {"city": "北京"}}
执行以 under operation: 1. 将年龄增加2岁 2. 添加一个 new 爱 good "programming" 3. 将城市改 for " on 海" 4. 添加一个 new 字段"email", 值 for "zhangsan@example.com"

referenceimplementation:

// 1. 将年龄增加2岁
db.users.updateOne(
    { "name": "张三" },
    { "$inc": { "age": 2 } }
)

// 2. 添加一个 new  爱 good "programming"
db.users.updateOne(
    { "name": "张三" },
    { "$push": { "hobbies": "programming" } }
)

// 3. 将城市改 for " on 海"
db.users.updateOne(
    { "name": "张三" },
    { "$set": { "address.city": " on 海" } }
)

// 4. 添加一个 new 字段"email"
db.users.updateOne(
    { "name": "张三" },
    { "$set": { "email": "zhangsan@example.com" } }
)