MongoDB基本操作

MongoDB基本操作

插入文档

建立集合

如果该集合当前不存在,则插入操作将创建该集合。

db.<集合>.insertOne(<JSON对象>) 将单个文档插入集合中。

> db.user.insertOne({name:"张三",age:NumberInt(18)});
{
        "acknowledged" : true,                             
        "insertedId" : ObjectId("61ef68aad2a832b51d376cac")
}
>

db.<集合>.insertMany([<JSON 1>, <JSON 2>, …])

db.user.insertMany([{
    name: "李四",
    age: NumberInt(19)
}, {
    name: "王五",
    age: NumberInt(20)
}, {
    name: "泥人张",
    age: NumberInt(89)
}]);

{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("61ef68b5be7c00001500276d"),
        ObjectId("61ef68b5be7c00001500276e"),
        ObjectId("61ef68b5be7c00001500276f")
    ]
}

MongoDB中的所有写操作都是单个文档级别的原子操作。

MongoDB提供了以下方法将文件插入集合:

方法备注
db.collection.insertOne()将单个文档插入到集合中。
db.collection.insertMany()将多个文件插入集合中。
db.collection.insert()将单个文档或多个文档插入到集合中。
查询文档

关于find:

  • find是MongoDB中查询数据的基本指令,相当于SQL中的SELECT。
  • find返回的是游标。

find示例:

db.user.find({name:"张三"}) //单条件查询
db.user.find({name:"张三",age:NumberInt(18)}) //多条件and查询
db.user.find({$and:[{name:"张三"},{age:NumberInt(18)}]}) //and的另一种形式
db.user.find({$or:[{name:"张三"},{age:NumberInt(19)}]}) //多条件or查询
db.user.find({name:/张/}) //按正则表达式查找
SQLMongoQL
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}}
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: 匹配全部条件

查询全部查询和投影运算符请访问官方文档:Query and Projection Operators(v4.2):https://docs.mongodb.com/v4.2/reference/operator/query/

使用find搜索子文档

find支持使用“field.sub_field”的形式查询子文档。

要在作为嵌入/嵌套文档的字段上指定相等条件,请使用查询筛选文档{:}**,其中**是要匹配的文档。

插入示例文档:

db.employee.insertOne({
    name: "张三",
    age: NumberInt(18),
    hometown: {
        province: "Guangdong",
        city: "Shenzhen"
    }
});
{
    "acknowledged": true,
    "insertedId": ObjectId("61ef6e1bbe7c000015002770")
}

查询hometown字段中的province字段等于"Guangdong"的所有文档

db.employee.find({"hometown.province":"Guangdong"});
{
    "_id": ObjectId("61ef6e1bbe7c000015002770"),
    "name": "张三",
    "age": NumberInt("18"),
    "hometown": {
        "province": "Guangdong",
        "city": "Shenzhen"
    }
}

查询hometown等于{province:“Guangdong”}的所有文档

db.employee.find({"hometown":{province:"Guangdong"}}) //无结果

整个子文档上的相等匹配要求与指定的文档完全匹配,包括字段顺序。

db.employee.find({"hometown":{city: "Shenzhen",province:"Guangdong"}}) //无结果,子文档字段顺序不一致
db.employee.find({"hometown":{province:"Guangdong",city: "Shenzhen"}}) //有结果
使用find搜索数组

插入示例文档:

db.student.insertMany([
    {
        name: "张三",
        age: NumberInt(16),
        interest: ["singing", "swimming"],
        score: [100, 99, 90]
    },
    {
        name: "李四",
        age: NumberInt(15),
        interest: ["swimming", "reading", "shoping"],
        score: [98, 97, 100]
    },
    {
        name: "王五",
        age: NumberInt(16),
        interest: ["dancing", "reading", "painting", "writing"],
        score: [95, 92, 96]
    }
])
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("61efa33dbe7c000015002774"),
        ObjectId("61efa33dbe7c000015002775"),
        ObjectId("61efa33dbe7c000015002776")
    ]
}
匹配数组

要在数组上指定相等条件,请使用查询文档 { : } ,其中****是要匹配的精确数组,包括元素的顺序。

查询字段interest值是按指定顺序恰好具有两个元素"singing", "swimming"的数组

db.student.find({interest: ["singing", "swimming"]}); //有结果
db.student.find({interest: ["swimming", "singing"]}); //无结果,顺序不一致

如果要找到一个同时包含元素"reading"和"writing"的数组,而不考虑顺序或该数组中的其他元素,请使用$all运算符:

db.student.find({interest: {$all:["reading","writing"]}});
查询数组中的元素

要查询数组字段是否包含至少一个具有指定值的元素,请使用过滤器 {:} ,其中是元素值。

查询interest种包含"swimming"元素的文档:

db.student.find({interest: "swimming"});

以下操作查询数组score包含至少一个值大于99的元素的所有文档。

db.student.find({score:{$gt:99}})
为数组元素指定多个条件

在数组元素上指定复合条件时,可以指定查询,以使单个数组元素满足这些条件,或者数组元素的任何组合均满足条件。

使用数组元素上的复合过滤条件查询数组:

其中score数组包含某种组合满足查询条件的元素; 例如,一个元素可以满足大于91的条件,而另一个元素可以满足小于93的条件,或者单个元素可以满足以下两个条件:

db.student.find({score:{$gt:91,$lt:93}});
// 1
{
    "_id": ObjectId("61efa33dbe7c000015002774"),
    "name": "张三",
    "age": NumberInt("16"),
    "interest": [
        "singing",
        "swimming"
    ],
    "score": [
        100,
        99,
        90
    ]
}

// 2
{
    "_id": ObjectId("61efa33dbe7c000015002776"),
    "name": "王五",
    "age": NumberInt("16"),
    "interest": [
        "dancing",
        "reading",
        "painting",
        "writing"
    ],
    "score": [
        95,
        92,
        96
    ]
}
查询满足多个条件的数组元素

使用**$elemMatch**运算符可在数组的元素上指定多个条件,以使至少一个数组元素满足所有指定的条件。

以下示例查询在score数组中包含至少一个同时大于( g t ) 97 和 小 于 ( gt)97和小于 ( gt)97(lt)99的元素的文档:

db.student.find({score:{$elemMatch:{$gt:91,$lt:93}}});
{
    "_id": ObjectId("61efa33dbe7c000015002776"),
    "name": "王五",
    "age": NumberInt("16"),
    "interest": [
        "dancing",
        "reading",
        "painting",
        "writing"
    ],
    "score": [
        95,
        92,
        96
    ]
}
通过数组索引位置查询元素

使用点表示法,可以为元素在数组的特定索引或位置处指定查询条件。 该数组使用基于零的索引。

使用点符号查询时,字段和嵌套字段必须在引号内。

以下示例查询数组score中第2个元素大于98的所有文档

db.student.find({"score.1":{$gt:98}})
通过数组长度查询数组

使用**$size**运算符可按元素数量查询数组。 例如,以下选择数组interest具有4个元素的文档:

db.student.find({interest:{$size:4}})
查询嵌入式文档数组

插入示例文档:

db.student.insertMany([{
    name: "张三",
    course_score: [{
        course: "数学",
        score: NumberInt(100)
    }, {
        course: "语文",
        score: NumberInt(98)
    }, {
        course: "外语",
        score: NumberInt(96)
    }]
}, {
    name: "李四",
    course_score: [{
        course: "数学",
        score: NumberInt(100)
    }, {
        course: "语文",
        score: NumberInt(99)
    }, {
        course: "外语",
        score: NumberInt(100)
    }]
}, {
    name: "王五",
    course_score: [{
        course: "数学",
        score: NumberInt(98)
    }, {
        course: "语文",
        score: NumberInt(98)
    }, {
        course: "外语",
        score: NumberInt(94)
    }]
}]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("61efc7fabe7c00001500277d"),
        ObjectId("61efc7fabe7c00001500277e"),
        ObjectId("61efc7fabe7c00001500277f")
    ]
}
查询嵌套在数组中的文档

下面的示例查询学科分数数组中的元素与指定学科分数{course: “数学”,score: NumberInt(100)}文档匹配的所有文档:

整个嵌套文档上的相等匹配要求与指定文档(包括字段顺序)完全匹配。

db.student.find({course_score:{course: "数学",score: NumberInt(100)}})

// 1
{
    "_id": ObjectId("61efc7fabe7c00001500277d"),
    "name": "张三",
    "course_score": [
        {
            "course": "数学",
            "score": NumberInt("100")
        },
        {
            "course": "语文",
            "score": NumberInt("98")
        },
        {
            "course": "外语",
            "score": NumberInt("96")
        }
    ]
}

// 2
{
    "_id": ObjectId("61efc7fabe7c00001500277e"),
    "name": "李四",
    "course_score": [
        {
            "course": "数学",
            "score": NumberInt("100")
        },
        {
            "course": "语文",
            "score": NumberInt("99")
        },
        {
            "course": "外语",
            "score": NumberInt("100")
        }
    ]
}

db.student.find({course_score:{score: NumberInt(100),course: "数学"}}); //无结果
在文档数组中的字段上指定查询条件

在嵌入文档数组中的字段上指定查询条件,如果不知道嵌套在数组中的文档的索引位置,请使用点(.)和嵌套文档中的字段名称来连接数组字段的名称。

下面的示例查询所有course_score数组中包含至少一个嵌入式文档的嵌入式文档,这些文档包含score>=99:

db.student.find({"course_score.score":{$gte:99}})
使用数组索引来查询嵌入式文档中的字段

使用点表示法,可以为文档中特定索引或数组位置的字段指定查询条件。 该数组使用基于零的索引。

使用点表示法查询时,字段和索引必须在引号内。

选择了所有course_score数组的第一个元素是一个包含值小于100的文档

db.student.find({"course_score.0.score":{$lt:100}})
为文档数组指定多个条件

在嵌套在文档数组中的多个字段上指定条件时,可以指定查询,以使单个文档满足这些条件,或者数组中文档的任何组合(包括单个文档)都满足条件。

使用** e l e m M a t c h ∗ ∗ 运 算 符 可 在 一 组 嵌 入 式 文 档 上 指 定 多 个 条 件 , 以 使 至 少 一 个 嵌 入 式 文 档 满 足 所 有 指 定 条 件 。 即 : 在 数 组 中 搜 索 子 对 象 的 多 个 字 段 时 , 如 果 使 用 elemMatch**运算符可在一组嵌入式文档上指定多个条件,以使至少一个嵌入式文档满足所有指定条件。即:在数组中搜索子对象的多个字段时,如果使用 elemMatch使使elemMatch,它表示必须是同一个子对象满足多个条件。

db.student.find({"course_score":{$elemMatch:{score:98,course:"数学"}}});

db.student.find({course_score:{course: "数学",score: NumberInt(100)}}); //注意区别
元素组合满足标准

如果数组字段上的复合查询条件未使用 $elemMatch 运算符,则查询将选择其数组包含满足条件的元素的任意组合的那些文档。

以下查询匹配文档,其中嵌套在course_score数组中的任何文档的分数score字段大于96,并且阵列中任何文档(但不一定是同一嵌入文档)的分数score字段小于98:

db.student.find({"course_score.score":{$gt:96,$lt:98}});

// 1
{
    "_id": ObjectId("61efc7fabe7c00001500277d"),
    "name": "张三",
    "course_score": [
        {
            "course": "数学",
            "score": NumberInt("100")
        },
        {
            "course": "语文",
            "score": NumberInt("98")
        },
        {
            "course": "外语",
            "score": NumberInt("96")
        }
    ]
}

// 2
{
    "_id": ObjectId("61efc7fabe7c00001500277f"),
    "name": "王五",
    "course_score": [
        {
            "course": "数学",
            "score": NumberInt("98")
        },
        {
            "course": "语文",
            "score": NumberInt("98")
        },
        {
            "course": "外语",
            "score": NumberInt("94")
        }
    ]
}
控制find 返回的字段
  • find 可以指定只返回指定的字段;

  • _id字段必须明确指明不返回,否则默认返回;

  • 在MongoDB 中我们称这为投影(projection);

  • db.student.find({name:“张三”},{_id:0,name:1});不返回_id,返回name

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

以下示例:

  • db.testcol.remove( { a : 1 } ) // 删除a 等于1的记录
  • db.testcol.remove( { a : { $lt : 5 } } ) // 删除a 小于5的记录
  • db.testcol.remove( { } ) // 删除所有记录
  • db.testcol.remove() //报错
方法备注
db.collection.deleteOne()即使多个文档可能与指定过滤器匹配,也最多删除一个与指定过滤器匹配的文档。
db.collection.deleteMany()删除所有与指定过滤器匹配的文档。
db.collection.remove()删除单个文档或与指定过滤器匹配的所有文档。
db.collection.findOneAndDelete()提供排序选项。该选项允许删除按指定 order 排序的第一个文档。
更新文档
方法备注
db.collection.updateOne()即使多个文档可能与指定的过滤器匹配,最多更新与指定的过滤器匹配的单个文档。
db.collection.updateMany()更新所有与指定过滤器匹配的文档。
db.collection.replaceOne()即使多个文档可能与指定过滤器匹配,也最多替换一个与指定过滤器匹配的文档。
db.collection.update()更新或替换与指定过滤器匹配的单个文档,或更新与指定过滤器匹配的所有文档。
db.collection.update()默认情况下,db.collection.update()方法更新单个文档。 要更新多个文档,请使用multi选项

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

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

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

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

    • s e t / set/ set/unset

    • p u s h / push/ push/pushAll/$pop

    • p u l l / pull/ pull/pullAll

    • $addToSet

使用update更新数组

  • $push: 增加一个对象到数组底部
  • $pushAll: 增加多个对象到数组底部
  • $pop: 从数组底部删除一个对象
  • $pull: 如果匹配指定的值,从数组中删除相应的对象
  • $pullAll: 如果匹配任意的值,从数据中删除相应的对象
  • $addToSet: 如果不存在则增加一个值到数组
删除集合
  • 使用db.<集合>.drop() 来删除一个集合
  • 集合中的全部文档都会被删除
  • 集合相关的索引也会被删除

示例:db.student.drop();

删除数据库
  • 使用db.dropDatabase() 来删除数据库
  • 数据库相应文件也会被删除,磁盘空间将被释放

示例

> show dbs
admin      0.000GB
config     0.000GB
local      0.000GB
mock       0.047GB
mongotest  0.000GB
> db
test
> use mongotest
switched to db mongotest
> db
mongotest
> db.dropDatabase();
{ "dropped" : "mongotest", "ok" : 1 }
> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB
mock    0.047GB
>

推荐文章:

MongoDB学习(七)$操作符表达式大全及实例:https://blog.csdn.net/qq_16313365/article/details/58599253

MongoDB 中文手册:https://docs.jinmu.info/MongoDB-Manual-zh/#/

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值