数据库操作

查看:show dbs;

创建:use dbname; // db.createCollection('collection_name');    隐式创建,需要创建的数据库中有表才表示创建成功

删除:use dbname; db.dropDatabase();   // 选择好对应的数据库,然后删除

如下实例:

查看数据库:

> show dbs;
admin 0.000GB
local 0.000GB
test_1 0.000GB
>

 创建数据库:隐式创建,直接use不存在的数据库

> use student;
switched to db student

查看没有:因为没有在这个数据库中创建表,只有创建表后才创建成功

> use student;
switched to db student
> show dbs;
admin 0.000GB
local 0.000GB
test_1 0.000GB

下面表示创建成功:

> use student;
switched to db student
> show dbs;
admin 0.000GB
local 0.000GB
test_1 0.000GB
>
> show collections;
>
> show tables;
> db.createCollection('minstudent');
{ "ok" : 1 }
> show tables;
minstudent
> show dbs;
admin 0.000GB
local 0.000GB
student 0.000GB
test_1 0.000GB

 删除数据库:

> db.dropDatabase();
{ "dropped" : "student", "ok" : 1 }
>

数据文档操作

这里的文档类似与MySQL中的表,因为Mongodb是文档数据库,所以可以说是对文档的操作;

创建:db.createCollection('collection_name');

删除:db.collection_name.drop();

查看:show collections;

如下实例:

创建

> use school;
switched to db school
>
> db.createCollection('student');
{ "ok" : 1 }

 删除

> db.student.drop();
true

 查看

> db.teacher.insert({'name':'teacher1'});
WriteResult({ "nInserted" : 1 })
> show collections;
teacher

文档内容操作

插入数据:db.collection_name.insert({key:value})  单个插入

db.collection_name.insert({_id:value, key:value}) 有_id的插入

db.collection_name.insert([{key:value},{key:value}])   多个插入

查看:db.collection_name.find();    // 这里只例举简单的查询方法,会单独写一篇文档详细说明查询的方法

删除:db.collection_name.remove(查询表达式,选项)

修改:db.collection_name.update(查询表达式,新值,选项)

如下实例:

插入

> db.student.insert({'name': 'wallace'});
WriteResult({ "nInserted" : 1 })
> db.student.find();
{ "_id" : ObjectId("5c810428cdad789abb91899a"), "name" : "wallace" }

 修改_id

> db.student.insert({'name': 'bbbb', '_id':111});
WriteResult({ "nInserted" : 1 })
> db.student.find();
{ "_id" : ObjectId("5c810428cdad789abb91899a"), "name" : "wallace" }
{ "_id" : ObjectId("5c810441cdad789abb91899b"), "name" : "bbbb" }
{ "_id" : 111, "name" : "bbbb" }

 插入多条

> db.student.insert([{'age': 'bbbb', 'age':111, 'home': 'beijin'},{'age':'laowang', 'age': 1, 'home':'江西'}]);
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 2,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
> db.student.find();
{ "_id" : ObjectId("5c810428cdad789abb91899a"), "name" : "wallace" }
{ "_id" : ObjectId("5c810441cdad789abb91899b"), "name" : "bbbb" }
{ "_id" : 111, "name" : "bbbb" }
{ "_id" : ObjectId("5c810567cdad789abb91899c"), "age" : 111, "home" : "beijin" }
{ "_id" : ObjectId("5c810567cdad789abb91899d"), "age" : 1, "home" : "江西"}

删除数据

> db.student.find();
{ "_id" : ObjectId("5c810428cdad789abb91899a"), "name" : "wallace" }
{ "_id" : ObjectId("5c810441cdad789abb91899b"), "name" : "bbbb" }
{ "_id" : 111, "name" : "bbbb" }
{ "_id" : ObjectId("5c810567cdad789abb91899c"), "age" : 111, "home" : "beijin" }
{ "_id" : ObjectId("5c810567cdad789abb91899d"), "age" : 1, "home" : "江西" }
{ "_id" : ObjectId("5c810575cdad789abb91899e"), "age" : 111, "home" : "beijin" }
{ "_id" : ObjectId("5c810575cdad789abb91899f"), "age" : 1, "home" : "江西" }
> db.student.remove({home:'beijin'});
WriteResult({ "nRemoved" : 2 })
> db.student.find();
{ "_id" : ObjectId("5c810428cdad789abb91899a"), "name" : "wallace" }
{ "_id" : ObjectId("5c810441cdad789abb91899b"), "name" : "bbbb" }
{ "_id" : 111, "name" : "bbbb" }
{ "_id" : ObjectId("5c810567cdad789abb91899d"), "age" : 1, "home" : "江西" }
{ "_id" : ObjectId("5c810575cdad789abb91899f"), "age" : 1, "home" : "江西" }
> db.student.remove({home:'江西'}, true);
WriteResult({ "nRemoved" : 1 })
> db.student.find();
{ "_id" : ObjectId("5c810428cdad789abb91899a"), "name" : "wallace" }
{ "_id" : ObjectId("5c810441cdad789abb91899b"), "name" : "bbbb" }
{ "_id" : 111, "name" : "bbbb" }
{ "_id" : ObjectId("5c810575cdad789abb91899f"), "age" : 1, "home" : "江西" }
>

修改

> db.student.find();
{ "_id" : ObjectId("5c810428cdad789abb91899a"), "name" : "wallace" }
{ "_id" : ObjectId("5c810441cdad789abb91899b"), "name" : "bbbb" }
{ "_id" : 111, "name" : "bbbb" }
{ "_id" : ObjectId("5c810575cdad789abb91899f"), "age" : 1, "home" : "江西" }
> db.student.update({home:'江西'},{home:北京});
2019-03-08T09:00:31.981-0500 E QUERY [thread1] ReferenceError: \u5317\u4EAC is not defined :
@(shell):1:32
> db.student.update({home:'江西'},{home:'北京'});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.student.find();
{ "_id" : ObjectId("5c810428cdad789abb91899a"), "name" : "wallace" }
{ "_id" : ObjectId("5c810441cdad789abb91899b"), "name" : "bbbb" }
{ "_id" : 111, "name" : "bbbb" }
{ "_id" : ObjectId("5c810575cdad789abb91899f"), "home" : "北京" }

修改二:$set 具体到某一个键值对的值

> db.student.insert({'name':'bbb',age:18, classmate:4});
WriteResult({ "nInserted" : 1 })
> db.student.update({name:'bbb'}, {$set:{'age':19}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.student.find();
{ "_id" : ObjectId("5c810428cdad789abb91899a"), "name" : "wallace" }
{ "_id" : ObjectId("5c810441cdad789abb91899b"), "name" : "1111" }
{ "_id" : 111, "name" : "bbbb" }
{ "_id" : ObjectId("5c810575cdad789abb91899f"), "home" : "北京" }
{ "_id" : ObjectId("5c835969043334857a7dbe85"), "name" : "aaa", "age" : 18, "classmate" : 3 }
{ "_id" : ObjectId("5c835973043334857a7dbe86"), "name" : "bbb", "age" : 19, "classmate" : 4 }

修改三:$unset 删除某一对象的键值对

> db.student.update({name:'bbb'}, {$unset:{'age':19}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.student.find();
{ "_id" : ObjectId("5c810428cdad789abb91899a"), "name" : "wallace" }
{ "_id" : ObjectId("5c810441cdad789abb91899b"), "name" : "1111" }
{ "_id" : 111, "name" : "bbbb" }
{ "_id" : ObjectId("5c810575cdad789abb91899f"), "home" : "北京" }
{ "_id" : ObjectId("5c835969043334857a7dbe85"), "name" : "aaa", "age" : 18, "classmate" : 3 }
{ "_id" : ObjectId("5c835973043334857a7dbe86"), "name" : "bbb", "classmate" : 4 }
>

修改列名

> db.student.update({name:'bbb'}, {$rename:{'name':'sc'}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.student.find();
{ "_id" : ObjectId("5c810428cdad789abb91899a"), "name" : "wallace" }
{ "_id" : ObjectId("5c810441cdad789abb91899b"), "name" : "1111" }
{ "_id" : 111, "name" : "bbbb" }
{ "_id" : ObjectId("5c810575cdad789abb91899f"), "home" : "北京" }
{ "_id" : ObjectId("5c835969043334857a7dbe85"), "name" : "aaa", "age" : 18, "classmate" : 3 }
{ "_id" : ObjectId("5c835973043334857a7dbe86"), "classmate" : 4, "sc" : "bbb" }
>

增加值

> db.student.find();
{ "_id" : ObjectId("5c810428cdad789abb91899a"), "name" : "wallace" }
{ "_id" : ObjectId("5c810441cdad789abb91899b"), "name" : "1111" }
{ "_id" : 111, "name" : "bbbb" }
{ "_id" : ObjectId("5c810575cdad789abb91899f"), "home" : "北京" }
{ "_id" : ObjectId("5c835969043334857a7dbe85"), "name" : "aaa", "age" : 37, "classmate" : 3 }
{ "_id" : ObjectId("5c835973043334857a7dbe86"), "classmate" : 4, "sc" : "bbb" }
> db.student.update({name:'aaa'},{$inc:{age:10}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.student.find();
{ "_id" : ObjectId("5c810428cdad789abb91899a"), "name" : "wallace" }
{ "_id" : ObjectId("5c810441cdad789abb91899b"), "name" : "1111" }
{ "_id" : 111, "name" : "bbbb" }
{ "_id" : ObjectId("5c810575cdad789abb91899f"), "home" : "北京" }
{ "_id" : ObjectId("5c835969043334857a7dbe85"), "name" : "aaa", "age" : 47, "classmate" : 3 }
{ "_id" : ObjectId("5c835973043334857a7dbe86"), "classmate" : 4, "sc" : "bbb" }
>

条件关键字

mongodb的条件查询与普通的SQL查询不一样,使用特定的符号来代替,下面表格的常用的的条件代替。

操作 格式 范例 RDBMS中的类似语句
等于 {<key>:<value>} db.col.find({"by":"aaa"}).pretty() where by = 'aaa'
小于 {<key>:{$lt:<value>}} db.col.find({"likes":{$lt:50}}).pretty() where likes < 50
小于或等于 {<key>:{$lte:<value>}} db.col.find({"likes":{$lte:50}}).pretty() where likes <= 50
大于 {<key>:{$gt:<value>}} db.col.find({"likes":{$gt:50}}).pretty() where likes > 50
大于或等于 {<key>:{$gte:<value>}} db.col.find({"likes":{$gte:50}}).pretty() where likes >= 50
不等于 {<key>:{$ne:<value>}} db.col.find({"likes":{$ne:50}}).pretty() where likes != 50

条件查询实例

1: 基础查询 where的练习:

查出满足以下条件的商品
1.1:主键为32的商品
db.goods.find({goods_id:32}); 1.2:不属第3栏目的所有商品($ne)
db.goods.find({cat_id:{$ne:3}},{goods_id:1,cat_id:1,goods_name:1}); 1.3:本店价格高于3000元的商品{$gt}
db.goods.find({shop_price:{$gt:3000}},{goods_name:1,shop_price:1}); 1.4:本店价格低于或等于100元的商品($lte)
db.goods.find({shop_price:{$lte:100}},{goods_name:1,shop_price:1}); 1.5:取出第4栏目或第11栏目的商品($in)
db.goods.find({cat_id:{$in:[4,11]}},{goods_name:1,shop_price:1}); 1.6:取出100<=价格<=500的商品($and)
db.goods.find({$and:[{price:{$gt:100},{$price:{$lt:500}}}]);
和下面方式结果一样:
db.goods.find({shop_price:{$gt:100}, shop_price:{$lt:5000}}, {goods_name:1, _id:0, goods_number:1, shop_price:1}) 1.7:取出不属于第3栏目且不属于第11栏目的商品($and $nin和$nor分别实现)
db.goods.find({$and:[{cat_id:{$ne:3}},{cat_id:{$ne:11}}]},{goods_name:1,cat_id:1})
db.goods.find({cat_id:{$nin:[3,11]}},{goods_name:1,cat_id:1});
db.goods.find({$nor:[{cat_id:3},{cat_id:11}]},{goods_name:1,cat_id:1}); 1.8:取出价格大于100且小于300,或者大于4000且小于5000的商品()
db.goods.find({$or:[{$and:[{shop_price:{$gt:100}},{shop_price:{$lt:300}}]},{$and:[{shop_price:{$gt:4000}},{shop_price:{$lt:5000}}]}]},{goods_name:1,shop_price:1}); 1.9:取出goods_id%5 == 1, 即,1,6,11,..这样的商品
db.goods.find({goods_id:{$mod:[5,1]}}); 1.10:取出有age属性的文档
db.stu.find({age:{$exists:1}});
含有age属性的文档将会被查出 1.11:使用where进行查询:
db.stu.find({$where:'this.goods_id>=3'}); // value直接接过滤条件

游标 cursor

游标不是查询结果,而是查询的返回资源,或者接口。类似与python中的生成器

通过调用可以逐条读取。直接将查询结果赋值给一个变量就是游标

var cursor = db.colllections_name.find(query, projection)
cursor.hasNext() //判断是否已经取完
cursor.Next() // 取出下一个元素

通常情况下我们用循环来获取游标中的值:

while循环

> var cursor=db.goods.find();
> while(cursor.hasNext()){
... printjson(cursor.next());}
{

for循环

> var cursor=db.goods.find();
> for(var doc=true;cursor.hasNext();){printjson(cursor.next())}

> for(var cursor=db.goods.find(); doc=true;cursor.hasNext()){printjson(cursor.next())}

forEach循环:可以自己添加回调函数

> var fun = function(obj){print(obj.goods_name)}; // 定义函数
> var cursor = db.goods.find(); // 创建游标
> cursor.forEach(fun); // 调用函数

游标分页:这个默认形式,也可以使用游标的形式

db.collection_name.find().skip(10); //表示跳过10开始取
db.collection_name.find().limit(10); //表示取10个

索引

索引提高查询速度,但会降低写入速度,所以再使用的时候需要权衡查询字段,不必在太多列上创建索引。在Mongodb中,索引可以按字段升序/降序来创建索引,便于排序。默认情况下mongodb是用btree来组织索引文件,2.4后也有通过hash来创建索引。

查看当前文档有那些索引

>db.collection_name.getIndexes()

创建普通索引(1表示升序,-1表示降序)

> db.collection_name.ensureIndex({field:})

创建多列索引

> db.collection_name.ensureIndex({field1:, field2:});

创建唯一索引

> db.collection_name.ensureIndex({field:},{unique:true});

创建hash索引

> db.collection_name.ensureIndex({field:'hashed'});

创建稀疏索引:如果针对field做索引,针对不含field列的文档将不做索引。而普通索引是会把该列作为null表示,并建立索引。

> db.collection_name.ensureIndex({name:}, {sparse:true});

重建索引

一个表经过很多次修改后,导致表的文件产生空洞,索引文件也是如此,可以通过索引重建,减少索引文件碎片,并提高索引的效率。类似mysql中的 optimize table

> db.collection_name.reIndex();

Mongodb 基础 查询表达式的更多相关文章

  1. Spring Data MongoDB 基础查询

    有两种方式查询 BasicQuery 和 Query 一.BasicQuery BasicQuery query = new BasicQuery("{ age : { $lt : 26 } ...

  2. mongodb基础系列——数据库查询数据返回前台JSP(一)

    经过一段时间停顿,终于提笔来重新整理mongodb基础系列博客了. 同时也很抱歉,由于各种原因,没有及时整理出,今天做了一个demo,来演示,mongodb数据库查询的数据在JSP显示问题. 做了一个 ...

  3. LINQ查询表达式基础

    LINQ,语言集成查询(Language Integrated Query)是一组用C#和Visual Basic语言的扩展. 对于编写查询的开发人员来说,LINQ 最明显的"语言集成&qu ...

  4. MongoDB基础教程系列--第四篇 MongoDB 查询文档

    查询文档 查询文档可以用 find() 方法查询全部文档,可以用 findOne() 查询第一个文档,当然还可以根据 条件操作符 和 $type操作符 查询满足条件的文档. find() 和 find ...

  5. 二、LINQ之查询表达式基础

    1.查询是什么? 查询是一组指令,描述要从给定数据源(或源)检索的数据以及返回的数据应具有的形状和组织.查询表达式和它所产生的结果不同.

  6. MongoDB 学习笔记之 查询表达式

    查询表达式: db.stu.find().count() db.stu.find({name: 'Sky'}) db.stu.find({age: {$ne: 20}},{name: 1, age: ...

  7. LINQ查询表达式(1) - 查询表达式基础

    LINQ包括五个部分:LINQto Objects.LINQ to DataSets.LINQ to SQL.LINQ to Entities.LINQ to XML. 什么是查询?它有什么用途? “ ...

  8. MongoDB基础学习

    *:first-child { margin-top: 0 !important; } body>*:last-child { margin-bottom: 0 !important; } /* ...

  9. mongodb基础学习2-基本CRUD

    接着学习一下mongodb的基本的CRUD 先列出基本知识点,再给出相关的例子 增:语法: db.collectionName.insert(document); 1: 增加单篇文档,不指定_id时会 ...

随机推荐

  1. 7.11js的总结

    <!DOCTYPE html> <html> <head> <title>js的内置全局函数</title> <script type ...

  2. meat http-equiv 属性详解

    转自 http://kinglyhum.iteye.com/blog/827807 http-equiv 属性提供了 content 属性的信息/值的 HTTP 头. http-equiv 属性可用于 ...

  3. 【吴恩达课后测验】Course 1 - 神经网络和深度学习 - 第一周测验【中英】

    [吴恩达课后测验]Course 1 - 神经网络和深度学习 - 第一周测验[中英] 第一周测验 - 深度学习简介 和“AI是新电力”相类似的说法是什么? [  ]AI为我们的家庭和办公室的个人设备供电 ...

  4. Unable to cast object of type 'System.Int32' to type 'System.Array'.

    x 入职了新公司.最近比较忙...一看博客...更新频率明显少了...罪过罪过... 新公司用ASP.NET MVC 遇上一个错误: Unable to cast object of type 'Sy ...

  5. CCPC-Wannafly Winter Camp Day5 Div1 - Sorting - [线段树]

    题目链接:https://zhixincode.com/contest/22/problem/I?problem_id=314 样例输入 1 5 9 31 5 3 2 41 1 52 1 51 1 1 ...

  6. 微信、QQ群短文本聊天语料总结

    在文本分类任务中,语料的特性千差万别,我们需要找到适合模型并抓住数据的特性,最终才能得到较好的model.最近在文本类别标注任务,就是给文本打标签确定该文本的类别.这是一个很费人工的过程,需要认真仔细 ...

  7. [skill][graphviz] 到底用什么画图: graphviz/inkscape/yed

    官方教程文档:http://www.graphviz.org/pdf/dotguide.pdf 一:在文档里抄一个简单的例子 /home/tong/Src/copyright/onescorpion/ ...

  8. cocos2dx 粒子系统

    参考文献: 1.http://blog.csdn.net/aa4790139/article/details/8126525 2.https://code.google.com/p/cocos2d-w ...

  9. day2_webservice接口怎么测-SoapUI

    可以用SoapUI工具测试 步骤: 1.新建soap project Ok后左侧出现接口内容 2.输入参数执行 3.根据需求文档的参数返回值做对比

  10. LeetCode 682 Baseball Game 解题报告

    题目要求 You're now a baseball game point recorder. Given a list of strings, each string can be one of t ...