美文网首页前端
mongodb基本操作

mongodb基本操作

作者: 麦都麦那麦 | 来源:发表于2020-04-27 15:00 被阅读0次

一、数据库基本操作


1.新建/切换数据库

use <database> 

2.查看所有数据库

show dbs 

3.显示你当前正在使用的数据库

db 

4.删除当前数据库

db.dropDatabase() 

二、表基本操作


1.新建表

db.createCollection("users") 

2.删除表

db.users.drop()  

3.查看数据库下所有表

show collections 

4.插入操作

常用插入操作

db.collection.insertOne({}) //插入单条数据 
db.collection.insertMany([{}]) //插入多条数据 
db.collection.insert() //插入单条或者多条数据 

5.查询操作

查询所有数据

db.users.find( {} ) 

user 集合中检索 status 字段值为 "A" 的所有文档(也适用于数组的模糊查询)

db.users.find( { status: "A" } ) 

user 集合中检索 status 字段值为 "P" 或者 "D" 的所有文档

db.users.find( { status: { $in: [ "P", "D" ] } } ) 

users 集合中检索 status 等于 "A"并且age 小于 ($lt) 30 的所有文档

db.users.find( { status: "A", age: { $lt: 30 } } ) 

users 集合中检索 status 等于 "A"或者age 小于 ($lt) 30 的所有文档

db.users.find( { $or: [ { status: "A" }, { age: { $lt: 30 } } ] } ) 

复合查询文档选择集合中status 等于 "A" 并且 要么 age 小于 ($lt) 30 要么 type等于 1 的所有文档

db.users.find( { status: "A", $or: [ { age: { $lt: 30 } }, { type: 1 } ] } ) 

匹配所有 favorites 字段下包含值等于 "Picasso" 的artist字段的文档 (也适用于数组的模糊查询)

db.users.find( { "favorites.artist": "Picasso" } ) 

数组上的精确匹配

db.users.find( { badges: [ "blue", "black" ] } ) 

数组上的匹配(忽略顺序)

db.inventory.find( { tags: { $all: ["red", "blank"] } } )

查询 badges 是一个数组字段并且包含black作为其数组元素的所有文档(也适用于对象精确查找)

db.users.find( { badges: "black" } ) 

查询数组dim_cm包含至少一个值大于25的元素的所有文档

db.inventory.find( { dim_cm: { $gt: 25 } } )

查询使用 the dot notation 匹配所有 dadges 数组的第一个元素为black的文档

db.users.find( { "badges.0": "black" } ) 

查询 finished 数组至少包含一个大于 (gt) 15 并且小于 (lt) 20 的元素的文档

db.users.find( { finished: { $elemMatch: { $gt: 15, $lt: 20 } } } ) 

按元素数量查询数组

db.inventory.find( { "tags": { $size: 3 } } )

嵌套数组 选择库存数组中的元素与指定文档匹配的所有文档,属性顺序和属性名和属性值以及属性个数都得完全一致
然后这里有个问题:怎么去匹配 含有 {warehouse: "A"}的集合呢? 答案是用$elemMatch元素匹配

[
{ item: "journal", instock: [ { warehouse: "A", qty: 5 }, { warehouse: "C", qty: 15 } ] }
]

db.inventory.find( { "instock": { warehouse: "A", qty: 5 } } )

嵌套数组 查询instock数组中元素含有qty属性且小于等于20的集合

db.inventory.find( { 'instock.qty': { $lte: 20 } } )

嵌套数组 查询instock数组中指定位置元素含有qty属性且小于等于20的集合

db.inventory.find( { 'instock.0.qty': { $lte: 20 } } )

嵌套数组 查询instock数组中元素集合有个值等于{ qty: 5 }的集合,注意:这里是具体的值而不是一种值的描述

db.inventory.find( { "instock": { qty: 5 } } )

嵌套数组 查询instock数组中元素含有qty和warehouse属性且值分别等于5和"A"集合,这里的elemMatch(元素匹配) 是一种模糊查询,区别于嵌套数组的精确查询,在对象数组中必须使用elemMatch来模糊匹配。然后又人要问了:那$elemMatch可以用在查询对象中的对象不?答案是否定的,对象中的对象用{"xxx.prop": "value"}来查询!

db.inventory.find( { "instock": { $elemMatch: { qty: 5, warehouse: "A" } } } )

嵌套数组 查询instock数组中至少一个包含qty等于5的嵌入式文档和至少一个包含warehouse等于A的字段仓库的嵌入式文档(但不一定是同一嵌入式文档)的文档。区别于$elemMatch是其中一条数据要包含{ qty: 5, warehouse: "A" }。 当属性只有一个的时候:db.inventory.find( { "instock": { $elemMatch: { warehouse: "A" }}} )与db.inventory.find( { "instock.warehouse": "A" } )效果是差不多的。最后注意一点:多 子属性条件查询对于数组来说就是 只要其中一个元素匹配到{ "qty": 5}(就代表instock能匹配到) 以及 其中一个元素匹配到{"warehouse": "A"}(就代表instock能匹配到)就符合条件。简单的理解就是“大哥没有的找小弟要,小弟有的就是大哥有的”

db.inventory.find( { "instock.qty": 5, "instock.warehouse": "A" } )

只返回了匹配文档的 name , status 以及默认的 _id 字段 ,如果不要返回_id,就加一个 _id: 0

db.users.find( { status: "A" }, { name: 1, status: 1 } ) 

在结果集中, favorites 和 points 字段不在匹配文档中返回

db.users.find( { status: "A" }, { favorites: 0, points: 0 } )

返回 _id 字段、name 字段、 status 字段以及 favorites 文档中的food 字段,
food 仍然保持嵌入在 favorites 文档中

db.users.find( { status: "A" }, { name: 1, status: 1, "favorites.food": 1 } ) 

使用 $slice 映射操作符来返回 points 数组中最后的元素 截取筛选操作

db.users.find({status: "A"},{name:1,status:1,points: {$slice: -1}} ) 

仅仅 匹配那些包含值是 null 的 name 字段的文档, $type相当于代表:有值且属于某某类型

db.users.find( { name : { $type: 10 } } ) 

查找不存在name字段的文档

db.users.find( { name : { $exists: false } } ) 

游标操作:.hasNext()、.next()、.toArray()

var myCursor = db.users.find( { type: 2 } );
while (myCursor.hasNext()) {
   print(tojson(myCursor.next()));
   //或者 printjson(myCursor.next());
}
或者
myCursor.forEach(printjson);

打印出json(在mongo shell中,可以使用toArray()方法来迭代游标并以数组形式返回文档)

var myCursor = db.user.find({})
print(tojson(myCursor.toArray()))

文本搜索

新建文本索引
db.stores.createIndex( { name: "text", description: "text" } )

查找含有以下文本的文档(模糊查询,不区分大小写)
db.stores.find( { $text: { $search: "java coffee shop", $caseSensitive: false } } )

查找含有以下文本的文档(含有单词边界)
db.stores.find( { $text: { $search: "\"coffee shop\"" } } )

查找含有以下文本的文档(含有排除项)
db.stores.find( { $text: { $search: "java shop -coffee" } } )

查询结果展示出匹配度分数,并排序
db.stores.find(
   { $text: { $search: "java coffee shop" } },
   { score: { $meta: "textScore" } }
).sort( { score: { $meta: "textScore" } } )

聚合管道中的文本搜索

!!!

地理空间查询

!!!

6.修改操作

使用集合db.collection.updateOne()上的 方法 inventory
更新第一个文档,其中 item equals "paper",并且设置当前时间在lastModified字段上

db.inventory.updateOne( { item: "paper" }, { $set: { "size.uom": "cm", status: "P" }, $currentDate: { lastModified: true } } )
或者
db.inventory.update( { item: "paper" }, { $set: { "size.uom": "cm", status: "P" }, $currentDate: { lastModified: true } } ) 

inventory更新qty小于50的所有文档,并且设置当前时间在lastModified字段上(类型为时间戳)

db.inventory.updateMany( { "qty": { $lt: 50 } }, { $set: { "size.uom": "in", status: "P" }, $currentDate: { lastModified: { $type: 'timestamp' } } } ) 

使用 db.collection.update() 并包含 multi: true 选项来更新多个文档

db.users.update( { "favorites.artist": "Pisanello" }, { $set: { "favorites.food": "pizza", type: 0, }, $currentDate: { lastModified: true } }, { multi: true } ) 

替换文档( _id字段不变)

db.inventory.replaceOne( {item: "paper"}, {item:"paper",instock:[{warehouse:"A",qty:60},{warehouse:"B",qty:40}]} ) 

聚合管道更新(难点)

!!!

7.删除操作

从 users 集合中删除所有文档

db.users.deleteMany({})
或者
db.users.remove({}) 

删除 第一个 status 字段等于 "D" 的文档

db.users.deleteOne( { status: "D" } )
或者
db.users.remove( { status: "D" }, 1) 

删除所有 status 字段等于 "A" 的文档:

db.users.deleteMany({ status : "A" }) 

集合中删除所有 status 字段等于 "P" 的文档

db.users.remove( { status : "P" } ) 

8.批量写入

bulkWrite支持以下操作:
insertOne、
updateOne、
updateMany、
replaceOne、
deleteOne、
deleteMany

try {
   db.characters.bulkWrite(
      [
         { insertOne :
            {
               "document" :
               {
                  "_id" : 4, "char" : "Dithras", "class" : "barbarian", "lvl" : 4
               }
            }
         },
         { insertOne :
            {
               "document" :
               {
                  "_id" : 5, "char" : "Taeln", "class" : "fighter", "lvl" : 3
               }
            }
         },
         { updateOne :
            {
               "filter" : { "char" : "Eldon" },
               "update" : { $set : { "status" : "Critical Injury" } }
            }
         },
         { deleteOne :
            { "filter" : { "char" : "Brisbane" } }
         },
         { replaceOne :
            {
               "filter" : { "char" : "Meldane" },
               "replacement" : { "char" : "Tanys", "class" : "oracle", "lvl" : 4 }
            }
         }
      ]
   );
}
catch (e) {
   print(e);
}

9.聚合管道

先匹配后分组
db.orders.aggregate([
   { $match: { status: "A" } },
   { $group: { _id: "$cust_id", total: { $sum: "$amount" } } }
])

$match 匹配
$sort 排序
$group 分组
$addFields 添加字段
$project 留下的字段
$skip 跳过条数
$limit 限制条数
$lookup 从其他collection中聚合操作
等常用操作

三、.查看帮助


help db.help() db.collection.help() 

相关文章

网友评论

    本文标题:mongodb基本操作

    本文链接:https://www.haomeiwen.com/subject/rggywhtx.html