《MongoDb权威指南》第二篇:简单使用_linux

第二篇 MongoDb的使用(linux)

1. 创建或切换到数据库

    子厚的操作均是在testDb中执行,除非只用user函数切换到其他db
user testdb

2. 查看可用的数据库和集合

show dbs
show collections

3. 在集合中插入数据

db.testdb.insertOne({
          
   json(Bson)数据})

4. 查询数据

#查询所有数据
db.testdb.find()

#查询单个文档
db.testdb.findOne()

#根据字段查询
db.testdb.find({
          
   "name" : "trunk liu"})

#查询指定字段(查询name为“trunk liu”记录的age字段)
db.testdb.find({
          
   "name" : "trunk liu"}, {
          
   "age" : 1})

#根据二级字段查询(二级字段必须精确匹配)
db.testdb.find("family.sisterName" : "AName")

#查询数组字段(查询Author包含“membrey,peter”)的记录
db.testdb.find({
          
   "Authos" : "membrey,peter"})

#查询总个数
db.testdb.find().count()

5. 使用sort、limit和skip

#排序sort:1代表升序,-1代表降序
db.testdb.find({
          
   "可添加条件" : "条件的值"}).sort({
          
   "字段" : 1})

#limit 查询前10条数据,可结合sort使用
db.testdb.find().limit(10)

#忽略前n个文档:skip
db.testdb.find().skip(20)

6.去重&分组 || distinct & group

#去重
db.testdb.distinct("字段")

#分组 : 用法不叫恶心,命令这里就不提供了

7.更新update

#更新一条数据:如果匹配多条数据,更新第一条
db.testdb.updateOne({
          
   "条件字段" : "value"}, {
          
   "updateFile" : "value", "file2" : "value"},{
          
   upsert : true})

#更新多条数据
db.testdb.updateMany({
          
   "条件字段" : "value"}, {
          
   "updateFile" : "value", "file2" : "value"},{
          
   upsert : true})

#upsert 代表查到就更新,没查到就新增

·····还有很多方法,暂不列举

8.重命名集合 & 删除数据

#重命名集合
db.testdb.renameCollection("newName")

#删除数据
db.testdb.deleteOne({
          
   "key" : "value"})

9.索引

#创建索引,1代表索引顺序为升序,-1为降序
db.testdb.CreateIndex({
          
   name : 1})
经验分享 程序员 微信小程序 职场和发展