mongodb简明教程

基本概念

  • Document
    MongoDB中数据的基本单元,非常类似于关系型数据系统中的行
  • Collection
    可以看成一个拥有动态模式的表,一个Collection里面的Document可以是各式各样的
  • Database
    一个MongoDB实例可以拥有多个相互独立的Database,每一个Database都拥有自己的集合
  • Mongo Shell
    MongoDB自带的一个简单但功能强大的JavaScript shell,可用于管理MongoDB的实例或数据操作

shell CRUD操作

创建

> use test
switched to db test
> post ={"title":"My Blog Post",
... "content":"Here's my blog post.",
...  "date":new Date()
...  }
{
    "title" : "My Blog Post",
    "content" : "Here's my blog post.",
    "date" : ISODate("2017-05-22T07:29:26.085Z")
}
//post是一个有效的文档,下面将其插入数据库
> db.blog.insert(post)
WriteResult({ "nInserted" : 1 })
//查询blog Collection,发现blog文档已经插入
> db.blog.find()
{ "_id" : ObjectId("5922935f01d2563bad1ad3f8"), "title" : "My Blog Post", "content" : "Here's my blog post.", "date" : ISODate("2017-05-22T07:29:26.085Z") }
>

读取

find和findOne可以接受一个查询文档作为限定文件。findOne代表只查看一个文档。

> db.blog.findOne()
{
    "_id" : ObjectId("5922935f01d2563bad1ad3f8"),
    "title" : "My Blog Post",
    "content" : "Here's my blog post.",
    "date" : ISODate("2017-05-22T07:29:26.085Z")
}

更新

> post.comments = []
[ ]
> db.blog.update({"title" : "My Blog Post"},post)
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.blog.find()
{ "_id" : ObjectId("5922935f01d2563bad1ad3f8"), "title" : "My Blog Post", "content" : "Here's my blog post.", "date" : ISODate("2017-05-22T07:29:26.085Z"), "comments" : [ ] }

update接受(至少)两个参数,第一个是限定条件(用于匹配待更新的文档),第二个是新的文档

删除

> db.blog.remove({"title" : "My Blog Post"})
WriteResult({ "nRemoved" : 1 })
> db.blog.find()
> 

remove可将数据库中的文档永久删除。如果没有传入参数,将会删除指定Collection中的全部文档,可以接受一个作为限定条件的文档为参数。

查询

//指定需要返回的键
> db.blog.find({},{"username":1})
{ "_id" : ObjectId("5922c9fb01d2563bad1ad3fb"), "username" : "Joe" }
//剔除查询结果中某些键
> db.blog.find({},{"username":0,"_id":0})
{ "email" : "joe@example.com", "address" : "Beijing" }

//查询条件 "$lt" "$lte" "$gt" "gte"
> db.users.find({"registered":{"$lt":new Date("01/01/2018")}})
{ "_id" : ObjectId("5922cb0601d2563bad1ad3fc"), "name" : "test", "email" : "test@example.com", "age" : 30, "registered" : ISODate("2017-05-22T11:26:45.167Z") }

//OR查询 "$in" "$or"
> db.raffle.find({"ticket_no":{"$in":[725,453,380]}})
> db.raffle.find({"$or":[{"ticket_no":735},{"winner":true}]})

// $not
> db.users.find({"id_num":{"$not":{"$mod":[5,1]}}})

//特定类型查询 null
> db.c.find({"y":null}) //此时返回了不含y键的document
{ "_id" : ObjectId("5922cdfd01d2563bad1ad3ff"), "y" : null }
{ "_id" : ObjectId("5922ce1e01d2563bad1ad400"), "z" : 1 }

> db.c.find({"y":{"$in":[null],"$exists":true}}) //因为没有$eq,采用$in操作符
{ "_id" : ObjectId("5922cdfd01d2563bad1ad3ff"), "y" : null }

//正则
> db.users.find({"name":/Test/i})
{ "_id" : ObjectId("5922cb0601d2563bad1ad3fc"), "name" : "test", "email" : "test@example.com", "age" : 30, "registered" : ISODate("2017-05-22T11:26:45.167Z") }

//查询数组(与查询标量值一样)
> db.food.insert({"fruit":["apple","banana"]})
WriteResult({ "nInserted" : 1 })
> db.food.find({"fruit":"banana"})
{ "_id" : ObjectId("5922cf2d01d2563bad1ad401"), "fruit" : [ "apple", "banana" ] }

//查询数组 $all 
> db.food.find({"fruit":{$all:["banana","apple"]}}) //$all对应数组,顺序无关
{ "_id" : ObjectId("5922cf2d01d2563bad1ad401"), "fruit" : [ "apple", "banana" ] }

//精确匹配
> db.food.find()
{ "_id" : ObjectId("5922cf2d01d2563bad1ad401"), "fruit" : [ "apple", "banana" ] }
> db.food.find({"fruit":["banana","apple"]})

//查询数组 $size
> db.food.find({"fruit":{"$size":2}})
{ "_id" : ObjectId("5922cf2d01d2563bad1ad401"), "fruit" : [ "apple", "banana" ] }

//查询数组 $slice
> db.blog.posts.find()
{ "_id" : ObjectId("5922d14801d2563bad1ad402"), "comments" : [ "d", "dadfs", "ddd", "good" ], "title" : "Nice Title" }
{ "_id" : ObjectId("5922d1d501d2563bad1ad403"), "criteria" : { "comments" : [ "d", "dadfs", "ddd", "good" ] } }
> db.blog.posts.findOne({},{"comments":{"$slice":2}})  //find第二个参数可选(可以指定需要返回的键),通过$slice操作可以返回某个键匹配的数组元素子集
{
    "_id" : ObjectId("5922d14801d2563bad1ad402"),
    "comments" : [
        "d",
        "dadfs"
    ],
    "title" : "Nice Title"
}
//指定数组区间
> db.blog.posts.findOne({},{"comments":{"$slice":[1,3]}})
{
    "_id" : ObjectId("5922d14801d2563bad1ad402"),
    "comments" : [
        "dadfs",
        "ddd",
        "good"
    ],
    "title" : "Nice Title"

//查询内嵌文档
{
    "content" : "dfadsf",
    "comments" : [
        {
            "author" : "joe",
            "score" : 3,
            "comment" : "nice post"
        },
        {
            "author" : "mary",
            "score" : 5,
            "comment" : "terrible post"
        }
    ]
}
> db.blog.insert(a)
WriteResult({ "nInserted" : 1 })
> db.blog.find({"comments":{"author":"joe","score":{"$gte":5}}}) //匹配为空,因为内嵌文档的匹配,必须要整个文档完全匹配
> db.blog.find({"comments":{"author":"joe","score":3,"comment":"nice post"}})
{ "_id" : ObjectId("5922d3d001d2563bad1ad404"), "content" : "dfadsf", "comments" : [ { "author" : "joe", "score" : 3, "comment" : "nice post" }, { "author" : "mary", "score" : 5, "comment" : "terrible post" } ] }

//使用$eleMatch匹配内嵌文档
> db.blog.find({"comments":{"$elemMatch":{"author":"joe","score":{"$gte":1}}}})
{ "_id" : ObjectId("5922d3d001d2563bad1ad404"), "content" : "dfadsf", "comments" : [ { "author" : "joe", "score" : 3, "comment" : "nice post" }, { "author" : "mary", "score" : 5, "comment" : "terrible post" } ] }

//limit skip sort
db.c.find().limit(3) //返回数量上限
db.c.find().skip(3)
db.c.find().sort({username:1,age:-1}) //1升序 -1降序


    原文作者:candice2cc
    原文地址: https://www.jianshu.com/p/27fc5c80a958
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞