MongoDB(一)基本操作

使用insert完成插入操作

操作格式:

  • db.<集合>.insertOne(<JSON对象>);
  • db.<集合>.insertMany([<JSON对象>,<JSON对象>,<JSON对象>]);

示例:

  • db.fruit.insertOne({name: "apple"});
  • db.fruit.insertMany([{name: "pear"}, {name: "orange"}])

使用find查询文档

  • 关于find
    • find是MongoDB中查询数据的基本指令,相当于SQL中的SELECT
    • find返回的是游标
  • find示例
    • db.movies.find({"year": 1975}) 单条件查询
    • db.movies.find({"year": 1989, "title": "Batman"}) //多条件and查询
    • db.movies.find({$and:[{"title": "Batman"}, {"category": "action"}]}) //and的另一种形式
    • db.movies.find({$and:[{"title": "Batman"}, {"category": "action"}]}) //多条件or查询
    • db.movies.find({"title": /^B/}) //按正则表达式查找

find()后追加.pretty()可以显示效果更友好

查询条件对照表

SQL MQL
a = 1 {a: 1}
a <> 1 {a: {$ne:1}}
a > 1 {a: {$gt: 1}}
a >= 1 {a: {$gte: 1}}
a < 1 {a: {$lt: 1}}
a <= 1 {a: {$lte: 1}}

查询逻辑对照表

SQL MQL
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 IS NULL {a: {$exists: false}}
a IN (1, 2, 3) {a: {$in: [1, 2, 3]}}

查询逻辑运算符

  • $lt: 存在并小于
  • $lte: 存在并小于等于
  • $gt: 存在并大于
  • $gte: 存在并大于等于
  • $ne: 不存在或存在但不等于
  • $in: 存在并在指定数组中
  • $nin: 不存在或不在指定数组中
  • $or: 匹配两个或多个条件中的一个
  • $and: 匹配全部条件

使用find搜索子文档

  • find支持使用“field.sub_field”的形式查询子文档。假设有一个文档:
db.fruit.insertOne({
    name: "apple",
    from: {
        "country": "China",
        "province": "Guangdong"
    }
})

//查找文档中“from.country”的值为"China"的
db.fruit.find({
    "from.country": "China"
})

//查找文档中有一个from并且值为country: "China"的
db.fruit.find({
    "from": {
        "country": "China"
    }
})

使用find搜索数组

db.fruit.insert(
[{
     name: "apple",
     color: ["red", "green"]
 },
 {
     name: "banana",
     color: ["green", "yellow"]
 }]
 )

 //检索color中包含green的
 db.fruit.find({
    color: "green"
 });

 //检索color中包含red或者yellow的
 db.fruit.find({
    $or: [
        {
            color: "red"
        },
        {
            color: "yellow"
        }
    ]
 })

使用find搜索数组中的对象

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"
        }
    ]
})

//查找城市是Rome的记录
db.movies.find({"filming_locations.city": "Rome"})
  • 在数组中搜索子对象的多个字段时,如果使用$elemMatch,它表示必须是同一个子对象满足多个条件

//city为Rome或country为USA的
db.movies.find({
    "filming_locations.city": "Rome",
    "filming_locations.country": "USA"
})

//city为Rome且country为USA的
db.movies.find({
    filming_locations: {
        $elemMatch: {
            city: "Rome",
            country: "USA"
        }
    }
})

控制find返回的字段

  • find可以指定只返回指定的字段
  • _id字段必须明确指明不返回,否则默认返回
  • 在MongoDB中我们称这为投影(projection)
  • db.movies.find({category: "action"}, {"_id":0, title: 1})
    • 不返回_id, 返回title
> db.movies.find({"filming_locations.city": "Rome"});
{ "_id" : ObjectId("5ebfa7ee84aeb68613b4cebe"), "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": 0, "title": 1});

{ "title" : "Raiders of the Lost Ark" }

//指定字段无条件检索
> db.movies.find({},{_id: 0, title: 1})
{ "title" : "Raiders of the Lost Ark" }

使用remove删除文档

  • remove命令需要配合查询条件使用
  • 匹配查询条件的文档会被删除
  • 指定一个空文档条件会删除所有文档

示例

db.testcol.insertMany([
{a: 1, b: 2},
{a: 1, b: 1},
{a: 2, b: 1},
{a: 3, b: 1},
{a: 7, b: 1}
])
  • db.testcol.remove({a: 1}); //删除a=1的记录
  • db.testcol.remove({a: {$lt: 5}}); //删除a<5的记录
  • db.testcol.remove({}); //删除所有记录
  • db.testcol.remove(); //报错

使用update更新文档

  • update操作执行格式: db.<集合>.update(<查询条件>, <更新字段>)

  • 以以下数据为例

    db.fruit.insertMany([
    {name: "apple"},
    {name: "pear"},
    {name: "orange"}
    ])
  • db.fruit.updateOne({name: "apple"}, {$set: {from: "China"}})

  • db.fruit.update({name: "apple"}, {$set: {from: "China"}})

  • db.fruit.updateMany({name: "apple"}, {$set: {from: "China"}});

  • 使用updateOne表示无论条件匹配多少条记录,始终只更新第一条;

  • 使用updateMany表示条件匹配多少条就更新多少条

  • updateOne/updateMany方法要求更新条件部分必须具有以下之一,否则将报错

    • \$set/$unset
    • \$push/\$pushAll/$pop
    • \$pull/$pullAll
    • $addToSet
  • 报错

    • db.fruit.updateOne({name: "apple"}, {from: "China"});

对数组的操作

  • $push: 增加一个对象到数组底部
  • $pop: 从数组底部删除一个对象
  • $pull: 如果匹配指定的值,从数组中删除相应的对象
  • $pullAll: 如果匹配任意的值,从数据中删除相应的对象
  • $addToSet: 如果不存在则增加一个值到数组

//插入示范数据
> db.users.insertMany([{name: "aa", list: [1]}, {name: "bb", list:[2]}, {name: "cc", list: [3]}, {name: "dd", list: [4]}]);
//查询数据
> db.users.find();
{ "_id" : ObjectId("5ec100292c16c3352e6ff14e"), "name" : "aa", "list" : [ 1 ] }
{ "_id" : ObjectId("5ec100292c16c3352e6ff14f"), "name" : "bb", "list" : [ 2 ] }
{ "_id" : ObjectId("5ec100292c16c3352e6ff150"), "name" : "cc", "list" : [ 3 ] }
{ "_id" : ObjectId("5ec100292c16c3352e6ff151"), "name" : "dd", "list" : [ 4 ] }

//$push
> db.users.update({name: "aa"}, {$push: {list: "aaa"}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.users.find({name: "aa"});
{ "_id" : ObjectId("5ec100292c16c3352e6ff14e"), "name" : "aa", "list" : [ 1, "aaa" ] }

//$push多个,不使用$each则会将后面的数组当成一个元素插入
> db.users.update({name: "bb"}, {$push: {list: {$each: [1, 2, 3]}}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.users.find({name: "bb"});
{ "_id" : ObjectId("5ec100292c16c3352e6ff14f"), "name" : "bb", "list" : [ 2, 1, 2, 3 ] }

//$pull(删除name为bb的对象中list为4的元素)
db.users.update({name: "bb"}, {$pull: {list: 4}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 0 })
> db.users.find({name: "bb"});
{ "_id" : ObjectId("5ec100292c16c3352e6ff14f"), "name" : "bb", "list" : [ 2, 1, 2, 3 ] }
//$pull(删除name为bb的对象中list中为2的元素)
> db.users.update({name: "bb"}, {$pull: {list: 2}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.users.find({name: "bb"});
{ "_id" : ObjectId("5ec100292c16c3352e6ff14f"), "name" : "bb", "list" : [ 1, 3 ] }

//给cc中添加一些元素
> db.users.update({name: "cc"}, {$push: {list: {$each: [1, 2, 3, 4, 5, 6]}}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.users.find({name: "cc"});
{ "_id" : ObjectId("5ec100292c16c3352e6ff150"), "name" : "cc", "list" : [ 3, 1, 2, 3, 4, 5, 6 ] }

//pullAll
> db.users.update({name: "cc"}, {$pullAll: {list: [1, 2, 3, 9, 10]}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.users.find({name: "cc"});
{ "_id" : ObjectId("5ec100292c16c3352e6ff150"), "name" : "cc", "list" : [ 4, 5, 6 ] }

//给dd中添加一些元素
> db.users.update({name: "dd"}, {$push: {list: {$each: [1, 2, 3, 4, 5, 6]}}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.users.find({name: "dd"});
{ "_id" : ObjectId("5ec103d92c16c3352e6ff152"), "name" : "dd", "list" : [ 4, 1, 2, 3, 4, 5, 6 ] }

//addToSet(插入集合中不存在的元素,存在的元素不重复插入)
//插入已经存在的1,插入失败
> db.users.update({name: "dd"}, {$addToSet: {list: 1}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 0 })
//list中存在为1的元素,则没有更新
> db.users.find({name: "dd"});
{ "_id" : ObjectId("5ec103d92c16c3352e6ff152"), "name" : "dd", "list" : [ 4, 1, 2, 3, 4, 5, 6 ] }

//插入不存在的7,插入成功
> db.users.update({name: "dd"}, {$addToSet: {list: 7}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.users.find({name: "dd"});
{ "_id" : ObjectId("5ec103d92c16c3352e6ff152"), "name" : "dd", "list" : [ 4, 1, 2, 3, 4, 5, 6, 7 ] }

//插入多个,也只会插入不存在的几个元素
> db.users.update({name: "dd"}, {$addToSet: {list: {$each: [1, 2, 3, 4, 9, 10, 11]}}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.users.find({name: "dd"});
{ "_id" : ObjectId("5ec103d92c16c3352e6ff152"), "name" : "dd", "list" : [ 4, 1, 2, 3, 4, 5, 6, 7, 9, 10, 11 ] }

使用drop来删除集合

  • 使用db.<集合>.drop()来删除一个集合;
  • 集合中的全部文档都会被删除
  • 集合相关的索引也会被删除

使用dropDatabase来删库

  • use <数据库名称>
  • 执行db.dropDatabase()来删除当前库

发表评论