MongoDb

Mongodb

数据库操作

#1、增
use config #如果数据库不存在,则创建数据库,否则切换到指定数据库。
 
#2、查
show dbs #查看所有
可以看到,我们刚创建的数据库config并不在数据库的列表中, 要显示它,我们需要向config数据库插入一些数据。
db.table1.insert({'a':1})
 
#3、删
use config #先切换到要删的库下
db.dropDatabase() #删除当前库

集合操作

#1、增
当第一个文档插入时,集合就会被创建
> use database1
switched to db database1
> db.table1.insert({'a':1})
WriteResult({ "nInserted" : 1 })
> db.table2.insert({'b':2})
WriteResult({ "nInserted" : 1 })
 
#2、查
> show tables
table1
table2
 
#3、删
> db.table1.drop()
true
> show tables
table2

文档操作

#1、没有指定_id则默认ObjectId,_id不能重复,且在插入后不可变
 
#2、插入单条
db.test.insert(user0)
user0={
    "name":"egon",
    "age":10,
    'hobbies':['music','read','dancing'],
    'addr':{
        'country':'China',
        'city':'BJ'
    }
}
 
db.test.insert(user0)
 
#3、插入多条 db.user.insertMany([user1,user2,user3,user4,user5])
 

or and not
# and
db.userinfo.find(
        {"name":"alex","age":23}
    )
 
# or
db.userinfo.find(
      {
      "$or":
      [{"name":"alex"},{"name":"bob"}]
      }
    )
  • $ne $gt $lt $gte $lte
db.user.find({'name':{"$ne":'alex'}})
in ,not it
db.user.find({"age":{"$in":[20,30,31]}})
取字段

find 的第二个参数

db.userinfo.find({
    "depart":"运营"
},{"name":1})
查询数组
#1、查看有dancing爱好的人
db.user.find({'hobbies':'dancing'})
 
#2、查看既有dancing爱好又有tea爱好的人
db.user.find({
    'hobbies':{
        "$all":['dancing','tea']
        }
})
 
#3、查看第4个爱好为tea的人
db.user.find({"hobbies.3":'tea'})
 
#4、查看所有人最后两个爱好
db.user.find({},{'hobbies':{"$slice":-2},"age":0,"_id":0,"name":0,"addr":0})
 
#5、查看所有人的第2个到第3个爱好
db.user.find({},{'hobbies':{"$slice":[1,2]},"age":0,"_id":0,"name":0,"addr":0})
 
> db.blog.find().pretty()
{
        "_id" : 1,
        "name" : "alex意外死亡的真相",
        "comments" : [
                {
                        "name" : "egon",
                        "content" : "alex是谁???",
                        "thumb" : 200
                },
                {
                        "name" : "wxx",
                        "content" : "我去,真的假的",
                        "thumb" : 300
                },
                {
                        "name" : "yxx",
                        "content" : "吃喝嫖赌抽,欠下两个亿",
                        "thumb" : 40
                },
                {
                        "name" : "egon",
                        "content" : "xxx",
                        "thumb" : 0
                }
        ]
}
db.blog.find({},{'comments':{"$slice":-2}}).pretty() #查询最后两个
db.blog.find({},{'comments':{"$slice":[1,2]}}).pretty() #查询1到2
 
排序
db.userinfo.find({"depart":"IT"}).sort({"age":1})
分页
.limit().skip()
数量
.count()

db.user.deleteOne({})
de.user.deleteMany({xx})
db.user.deleteMany({})

posted @ 2020-04-21 12:05  tangshuo!  阅读(129)  评论(0编辑  收藏  举报