首页 > 编程笔记 > MongoDB 阅读:12

MongoDB Shell基本操作详解(附带实例)

一般情况下,数据库支持命令以及图形化等多种方式来操作数据。在使用命令操作数据库时,MongoDB Shell 非常强大。只要版本适配,它就能够支持 MongoDB 提供的所有方法。

在使用数据库的过程中,最常用的就是对数据的增删改查,即新增、删除、修改和查询操作。

MongoDB Shell新增操作

通过 MongoDB Shell 可以使用如下方法实现文档记录的插入操作:

1) 插入单条文档

使用 db.collection.insertOne() 插入单条文档数据,如果数据中未指定 _id 字段的值,MongoDB 就会自动添加该字段的值。语句如下:
db.books.insertOne(
    {
        title: "兄弟",
        genres: [ "Novel", "Fiction" ],
        words: 500000,
        year: 2005,
        author: [ "余华" ],
        characters: [ "李光头", "宋钢", "宋凡平", "林红" ],
        country: "中国"
    }
)
执行结果如下:

{
    acknowledged: true,
    insertedId: ObjectId('658a8c079dff3c3d9957378b')
}

从运行结果可以看到,数据插入成功之后,会返回该条记录的 _id 值。

2) 插入多条文档

插入多条文档的语句如下:
db.books.insertMany([
    {
        title: "平凡的世界",
        genres: [ "Novel", "Fiction" ],
        words: 1040000,
        year: 1986,
        author: [ "路遥" ],
        characters: [ "孙少平", "孙少安", "田晓霞", "田润叶" ],
        country: "中国"
    },
    {
        title: "活着",
        genres: [ "Novel" ],
        words: 132000,
        year: 1992,
        author: [ "余华" ],
        characters: [ "徐福贵", "家珍", "凤霞", "有庆" ],
        country: "中国"
    }
])
执行结果为:

{
    acknowledged: true,
    insertedIds: {
        '0': ObjectId('658a8c379dff3c3d9957378c'),
        '1': ObjectId('658a8c379dff3c3d9957378d')
    }
}

从图中可以看出,插入多条文档后,会返回每一条数据的 _id 字段值。

MongoDB Shell查询操作

查询文档数据使用命令 db.collection.find(),该命令会返回集合中的所有文档:
reading> db.books.find()
[
    {
        _id: ObjectId('658a8c079dff3c3d9957378b'),
        title: "兄弟",
        genres: [ "Novel", "Fiction" ],
        words: 500000,
        year: 2005,
        author: [ "余华" ],
        characters: [ "李光头", "宋钢", "宋凡平", "林红" ],
        country: "中国"
    },
    {
        _id: ObjectId('658a8c379dff3c3d9957378c'),
        title: "平凡的世界",
        genres: [ "Novel", "Fiction" ],
        words: 1040000,
        year: 1986,
        author: [ "路遥" ],
        characters: [ "孙少平", "孙少安", "田晓霞", "田润叶" ],
        country: "中国"
    },
    {
        _id: ObjectId('658a8c379dff3c3d9957378d'),
        title: "活着",
        genres: [ "Novel" ],
        words: 132000,
        year: 1992,
        author: [ "余华" ],
        characters: [ "徐福贵", "家珍", "凤霞", "有庆" ],
        country: "中国"
    }
]
该语句跟下面的 SQL 语句作用相同:
SELECT * FROM books

除查询全部文档外,还可以使用命令 <field>:<value>指定字段值来过滤文档。例如,查询书名为《活着》的书,命令如下:
db.books.find( { "title": "活着" } )
执行结果为:
reading> db.books.find( { "title": "活着" } )
[
    {
        _id: ObjectId('658a8c379dff3c3d9957378d'),
        title: "活着",
        genres: [ "Novel" ],
        words: 132000,
        year: 1992,
        author: [ "余华" ],
        characters: [ "徐福贵", "家珍", "凤霞", "有庆" ],
        country: "中国"
    }
]
该条语句等同于如下 SQL 语句:
SELECT * FROM books WHERE title = "活着"

除此之外,还可以使用查询操作符来查询数据,语法如下:
{ <field1>: { <operator1>: <value1> }, }

查询 1986 年和 1992 年发表的作品,命令如下:
db.books.find( { year: { $in: [ 1986, 1992] } } )
执行结果为:
reading> db.books.find( { year: { $in: [ 1986, 1992] } } )
[
    {
        _id: ObjectId('658a8c379dff3c3d9957378c'),
        title: "平凡的世界",
        genres: [ "Novel", "Fiction" ],
        words: 1040000,
        year: 1986,
        author: [ "路遥" ],
        characters: [ "孙少平", "孙少安", "田晓霞", "田润叶" ],
        country: "中国"
    },
    {
        _id: ObjectId('658a8c379dff3c3d9957378d'),
        title: "活着",
        genres: [ "Novel" ],
        words: 132000,
        year: 1992,
        author: [ "余华" ],
        characters: [ "徐福贵", "家珍", "凤霞", "有庆" ],
        country: "中国"
    }
]
该条语句等同于如下 SQL 语句:
SELECT * FROM b WHERE year in (1986, 1992)

使用逻辑运算符查询数据,$gte 表示大于,例如查找 2000 年以后发表的作品,命令如下:
db.books.find( { country: "中国", "year": { $gte: 2000 } } )
默认情况下,语句中的条件是 and,即“且”的关系。如果使用“或”关系,可在语句中加入 $or 关键字。

例如查询属于中国的且字数在 60 万字以上或者在 2005 年发表的作品。命令如下:
reading> db.books.find( {
    country: "中国",
    $or: [ { "words": { $gte: 600000 } }, { year: 2005 } ]
} )
执行结果为:
[
    {
        _id: ObjectId('658a8c079dff3c3d9957378b'),
        title: "兄弟",
        genres: [ "Novel", "Fiction" ],
        words: 500000,
        year: 2005,
        author: [ "余华" ],
        characters: [ "李光头", "宋钢", "宋凡平", "林红" ],
        country: "中国"
    },
    {
        _id: ObjectId('658a8c379dff3c3d9957378c'),
        title: "平凡的世界",
        genres: [ "Novel", "Fiction" ],
        words: 1040000,
        year: 1986,
        author: [ "路遥" ],
        characters: [ "孙少平", "孙少安", "田晓霞", "田润叶" ],
        country: "中国"
    }
]
$or 关键字标记的语句属于或的关系,整个 $or 与外面的 country 查询条件构成“且”的关系。

MongoDB Shell修改操作

MongoDB Shell 提供如下有关修改的操作语句:

1) 更新操作符

更新操作符的语法格式如下:
{
    <update operator>: { <field1>: <value1>, },
    <update operator>: { <field2>: <value2>, },
    ...
}

2) 更新单个文档

使用 db.collection.updateOne() 更新单个文档。默认情况下,MongoDB 会更新符合查询条件结果集的第一条文档。

例如,更新书名为《活着》的作品简介,并记录更新时间,语句如下:
db.books.updateOne( { title: "活着" },
    {
        $set: {
            plot: "讲解一个人一生的故事,这是一个历尽世间沧桑和磨难老人的人生感言,是一幕演绎人生苦难经历的戏剧。"
        },
        $currentDate: { lastUpdated: true }
    }
)
执行结果为:

{
    acknowledged: true,
    matchedCount: 1,
    modifiedCount: 1,
    insertedId: null
}


此条语句中用到了 $set 操作符,更新了 plot 字段值。$currentDate 操作符更新了 lastUpdated 字段值。如果以上字段不存在,操作符会自动创建相应的字段并赋值。数据成功更新后,执行查询语句查看该条文档数据,可以看到 plot 和 lastUpdated 字段:
reading> db.books.find({title:"活着"})
[
    {
        _id: ObjectId('658a8c379dff3c3d9957378d'),
        title: '活着',
        genres: [ 'Novel' ],
        words: 132000,
        year: 1992,
        author: [ '余华' ],
        characters: [ '徐福贵', '家珍', '凤霞', '有庆' ],
        country: '中国',
        lastUpdated: ISODate('2023-12-26T08:42:3.419Z'),
        plot: '讲述一个人一生的故事,这是一个历尽世间沧桑和磨难老人的人生感言,是一幕演绎人生苦难经历的戏剧。'
    }
]

3) 更新多个文档

使用 db.collection.updateMany() 更新多个文档,该语句会更新满足查询条件的结果集的所有文档。

例如,给字数在 10 万字以上的书加上标签“长篇”,语句如下:
db.books.updateMany(
    { words: { $gte: 100000 } },
    {
        $set: { tags: [ "长篇" ] }
    }
)
执行结果为:

{
    acknowledged: true,
    insertedId: null,
    matchedCount: 3,
    modifiedCount: 3,
    upsertedCount: 0
}

从运行结果可以看到,matchedCount 为 3,表示匹配的记录有 3 条,modifiedCount 为 3,表示被更新的记录有 3 条。

更新成功后,查询对应数据,可以看到数据已成功更新:
reading> db.books.find()
[
    {
        _id: ObjectId('658a8c079dff3c3d9957378b'),
        title: '兄弟',
        genres: [ 'Novel', 'Fiction' ],
        words: 500000,
        year: 2005,
        author: [ '余华' ],
        characters: [ '李光头', '宋钢', '宋凡平', '林红' ],
        country: '中国',
        tags: [ '长篇' ]
    },
    {
        _id: ObjectId('658a8c379dff3c3d9957378c'),
        title: '平凡的世界',
        genres: [ 'Novel', 'Fiction' ],
        words: 1040000,
        year: 1986,
        author: [ '路遥' ],
        characters: [ '孙少平', '孙少安', '田晓霞', '田润叶' ],
        country: '中国',
        tags: [ '长篇' ]
    },
    {
        _id: ObjectId('658a8c379dff3c3d9957378d'),
        title: '活着',
        genres: [ 'Novel' ],
        words: 132000,
        year: 1992,
        author: [ '余华' ],
        characters: [ '徐福贵', '家珍', '凤霞', '有庆' ],
        country: '中国',
        lastUpdated: ISODate('2023-12-26T08:42:35.419Z'),
        plot: '讲述一个人一生的故事,这是一个历尽世间沧桑和磨难老人的人生感言,是一幕演绎人生苦难经历的戏剧。',
        tags: [ '长篇' ]
    }
]

4) 替换单个文档

使用语句 db.collection.replaceOne() 替换符合查询条件的结果集的第一个文档。

例如将《兄弟》这本书的内容全部修改为《在细雨中呐喊》的内容。语句如下:
db.books.replaceOne(
    {title: "兄弟"},
    {
        title: "在细雨中呐喊",
        genres: [ "Novel", "Fiction" ],
        words: 500000,
        year: 1991,
        author: [ "余华" ],
        characters: [ "孙光林", "孙光平", "孙光明" ],
        country: "中国"
    }
)
执行结果为:
reading> db.books.replaceOne(
    {title: "兄弟"},
    {
        title: "在细雨中呐喊",
        genres: [ "Novel", "Fiction" ],
        words: 500000,
        year: 1991,
        author: [ "余华" ],
        characters: [ "孙光林", "孙光平", "孙光明" ],
        country: "中国"
    }
)
{
    acknowledged: true,
    insertedId: null,
    matchedCount: 1,
    modifiedCount: 1,
    upsertedCount: 0
}
替换语句不会操作 _id 字段,所以在更新的内容中可以忽略该字段,如果在更新语句中有 _id 字段的值,确保与要替换的文档记录的 _id 字段值一致。

替换成功后,执行查询语句:
reading> db.books.find()
[
    {
        _id: ObjectId('658a8c079dff3c3d9957378b'),
        title: '在细雨中呐喊',
        genres: [ 'Novel', 'Fiction' ],
        words: 500000,
        year: 1991,
        author: [ '余华' ],
        characters: [ '孙光林', '孙光平', '孙光明' ],
        country: '中国',
        tags: [ '长篇' ]
    },
    {
        _id: ObjectId('658a8c379dff3c3d9957378c'),
        title: '平凡的世界',
        genres: [ 'Novel', 'Fiction' ],
        words: 1040000,
        year: 1986,
        author: [ '路遥' ],
        characters: [ '孙少平', '孙少安', '田晓霞', '田润叶' ],
        country: '中国',
        tags: [ '长篇' ]
    },
    {
        _id: ObjectId('658a8c379dff3c3d9957378d'),
        title: '活着',
        genres: [ 'Novel' ],
        words: 132000,
        year: 1992,
        author: [ '余华' ],
        characters: [ '徐福贵', '家珍', '凤霞', '有庆' ],
        country: '中国',
        lastUpdated: ISODate('2023-12-26T08:42:3.419Z'),
        plot: '讲述一个人一生的故事,这是一个历尽世间沧桑和磨难老人的人生感言,是一幕演绎人生苦难经历的戏剧。',
        tags: [ '长篇' ]
    }
]
可以看到书的信息已被替换,但 _id 字段未发生改变。

MongoDB Shell删除操作

删除的语法格式如下:

1) 删除所有数据

db.books.deleteMany({})
此条语句慎用,会删除集合的全部文档数据。

2) 删除满足条件的所有文档

删除书名为《平凡的世界》的作品,命令如下:
db.books.deleteMany( { title: "平凡的世界" } )
执行结果为:
reading> db.books.deleteMany( { title: "平凡的世界" } )
{
    acknowledged: true,
    deletedCount: 1
}

删除完成后,执行查询语句:
reading> db.books.find()
[
    {
        _id: ObjectId('658a8c079dff3c3d9957378b'),
        title: '在细雨中呐喊',
        genres: [ 'Novel', 'Fiction' ],
        words: 500000,
        year: 1991,
        author: [ '余华' ],
        characters: [ '孙光林', '孙光平', '孙光明' ],
        country: '中国',
        tags: [ '长篇' ]
    },
    {
        _id: ObjectId('658a8c379dff3c3d9957378d'),
        title: '活着',
        genres: [ 'Novel' ],
        words: 132000,
        year: 1992,
        author: [ '余华' ],
        characters: [ '徐福贵', '家珍', '凤霞', '有庆' ],
        country: '中国',
        lastUpdated: ISODate('2023-12-26T08:42:35.419Z'),
        plot: '讲述一个人一生的故事,这是一个历尽世间沧桑和磨难老人的人生感言,是一幕演绎人生苦难经历的戏剧。',
        tags: [ '长篇' ]
    }
]

3) 删除满足条件的单个文档

删除作者“余华”的其中一本书,语句如下:
db.books.deleteOne( { author: "余华" } )
执行结果为:
db.books.deleteOne( { author: "余华" } )
{
    acknowledged: true,
    deletedCount: 1
}

删除完成后,执行查询语句:
reading> db.books.find()
[
    {
        _id: ObjectId('658a8c079dff3c3d9957378b'),
        title: '在细雨中呐喊',
        genres: [ 'Novel', 'Fiction' ],
        words: 500000,
        year: 1991,
        author: [ '余华' ],
        characters: [ '孙光林', '孙光平', '孙光明' ],
        country: '中国',
        tags: [ '长篇' ]
    }
]

相关文章