Easton's Blog Easton's Blog
首页
  • 编程语言

    • Python
  • 框架

    • Django
  • Mdn (opens new window)
  • HTML
  • CSS
  • JavaScript
  • Mysql
  • PostgreSQL
  • Elasticsearch
  • MongoDB
  • Redis
  • 服务器命令
  • Docker
  • GIT
  • 摄影
  • 草稿
  • 归类方式

    • 分类
    • 标签
    • 归档
  • 关于博客

    • 博客教程
    • 友情链接
    • 关于
导航站
GitHub (opens new window)

Easton Yang

爱生活😊爱学习
首页
  • 编程语言

    • Python
  • 框架

    • Django
  • Mdn (opens new window)
  • HTML
  • CSS
  • JavaScript
  • Mysql
  • PostgreSQL
  • Elasticsearch
  • MongoDB
  • Redis
  • 服务器命令
  • Docker
  • GIT
  • 摄影
  • 草稿
  • 归类方式

    • 分类
    • 标签
    • 归档
  • 关于博客

    • 博客教程
    • 友情链接
    • 关于
导航站
GitHub (opens new window)
  • Mysql

  • PostgreSQL

  • ES

  • MongoDB

    • SQL
      • 数据
      • 查询
        • 指定条件查询
        • $or
        • 区间
        • $in
        • limit 和 pretty
        • skip
        • sort
        • $exists
        • count
        • 案例
        • 返回指定字段
      • 插入
      • 更新
        • 更新一条数据的指定字段
        • 更新多条数据的指定字段
      • 删除
        • 删除一条数据
        • 删除多条数据
    • 聚合
  • Redis

  • 数据库
  • MongoDB
eastonyangxu
2023-07-13
目录

SQL

注意

python 操作 mongo 需要安装 pymongo。返回的结果是一个 pymongo.cursor.Cursor 迭代器。

pip 安装 pymongo:pip install pymongo

# 数据

点击下载:accounts_mongo.json 文件

import pymongo
import json

# 使用python批量插入数据,注意数据库名 和 表名
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
my_db = myclient["ts"]
my_table = my_db["accounts"]
with open('accounts_mongo.json') as f:
    data = f.readlines()
    data = [json.loads(s.replace('\r\n', '')) for s in data]
    my_table.insert_many(data)
1
2
3
4
5
6
7
8
9
10
11

# 查询

# 指定条件查询

类似于聚合的$match。

    // 多个条件时需要同时满足
    db.accounts.find({"firstname": "Amber", "lastname" : "Duke"})
    
    1
    2
    import pymongo
    db = pymongo.MongoClient("mongodb://localhost:27017/")["ts"]
    print(db.accounts.find({"firstname": "Amber", "lastname" : "Duke"}))
    
    1
    2
    3
    // Make sure to add code blocks to your code group

    # $or

    类似于聚合的$match。

      // or查询,满足其中之一即可。
      db.accounts.find({"$or": [{"firstname": "Amber"}, {"lastname" : "Davidson"}]})
      
      1
      2
      import pymongo
      db = pymongo.MongoClient("mongodb://localhost:27017/")["ts"]
      print(db.accounts.find({"$or": [{"firstname": "Amber"}, {"lastname" : "Davidson"}]}))
      
      1
      2
      3
      // Make sure to add code blocks to your code group

      # 区间

      $gt:大于、$gte:大于等于、$lt:小于、$lte:小于等于、$ne不等于

        // limit表示返回指定条数。
        db.accounts.find({"age": {"$gte": 10}}).limit(5)
        
        1
        2
        import pymongo
        db = pymongo.MongoClient("mongodb://localhost:27017/")["ts"]
        print(db.accounts.find({"age": {"$gte": 10}}).limit(5))
        
        1
        2
        3
        // Make sure to add code blocks to your code group

        # $in

          // 查询满足多个条件的结果。
          db.accounts.find({"age": {"$in": [10, 20, 30]}}).limit(5)
          
          1
          2
          import pymongo
          db = pymongo.MongoClient("mongodb://localhost:27017/")["ts"]
          print(db.accounts.find({"age": {"$in": [10, 20, 30]}}).limit(5))
          
          1
          2
          3
          // Make sure to add code blocks to your code group

          # limit 和 pretty

          指定返回数据条数,类似于聚合的$limit。

            // 返回1条数据,并且美化返回的结果。
            // pretty为了显示结果更直观,只在终端命令的时候才会使用。
            db.accounts.find({}).limit(1).pretty()
            // 第二种写法
            db.accounts.findOne()
            
            1
            2
            3
            4
            5
            import pymongo
            db = pymongo.MongoClient("mongodb://localhost:27017/")["ts"]
            print(db.accounts.find_one())
            
            1
            2
            3
            // Make sure to add code blocks to your code group

            # skip

            结合 limit 实现分页,类似于聚合的$skip。

              // 实现分页
              // 查询第五页,每页10条数据,skip表示跳过多少条开始查询。
              // 这里表示从第40条开始查询,查询10条结果。skip默认为0。
              db.accounts.find({}).skip(40).limit(10)
              
              1
              2
              3
              4
              import pymongo
              db = pymongo.MongoClient("mongodb://localhost:27017/")["ts"]
              print(db.accounts.find({}).skip(40).limit(10))
              
              1
              2
              3
              // Make sure to add code blocks to your code group

              # sort

              排序,-1:降序、1:升序,类似于聚合的$sort。

                // 按age降序,balance升序
                db.accounts.find().sort({"age": -1, "balance": 1})
                
                1
                2
                import pymongo
                db = pymongo.MongoClient("mongodb://localhost:27017/")["ts"]
                print(db.accounts.find().sort([("age", -1), ("balance", 1)]))
                
                1
                2
                3
                // Make sure to add code blocks to your code group

                # $exists

                true:字段存在、false:字段不存在

                  // 查询存在字段demo的数据
                  // 这里所有的数据中都没有demo,所以返回的结果为空。
                  db.accounts.find({"demo": {"$exists": true}})
                  
                  1
                  2
                  3
                  import pymongo
                  db = pymongo.MongoClient("mongodb://localhost:27017/")["ts"]
                  print(db.accounts.find({"demo": {"$exists": True}}))
                  
                  1
                  2
                  3
                  // Make sure to add code blocks to your code group

                  # count

                    // 返回结果的条数
                    db.accounts.find().count()
                    
                    1
                    2
                    import pymongo
                    db = pymongo.MongoClient("mongodb://localhost:27017/")["ts"]
                    print(db.accounts.find().count())
                    
                    1
                    2
                    3
                    // Make sure to add code blocks to your code group

                    # 案例

                      // 查询age在20-30之间,或者balance大于等于35000,并且state在IL、ME中,并且gender等于M,按age降序
                      db.accounts.find({
                        "$or": [
                          {"age": {"$gt": 20, "$lt": 30}},
                          {"balance": {"$gte": 35000}}
                        ],
                        "state": {"$in": ["IL", "ME"]},
                        "gender": "M"
                      }).sort({"age": -1})
                      
                      1
                      2
                      3
                      4
                      5
                      6
                      7
                      8
                      9
                      import pymongo
                      db = pymongo.MongoClient("mongodb://localhost:27017/")["ts"]
                      print(db.accounts.find({
                        "$or": [
                          {"age": {"$gt": 20, "$lt": 30}},
                          {"balance": {"$gte": 35000}}
                        ],
                        "state": {"$in": ["IL", "ME"]},
                        "gender": "M"
                      }).sort("age", -1))
                      
                      1
                      2
                      3
                      4
                      5
                      6
                      7
                      8
                      9
                      10
                      // Make sure to add code blocks to your code group

                      # 返回指定字段

                      0:不返回、1:返回,类似于聚合的$project。

                      注意

                      默认都会返回 _id 字段,如果不需要返回 _id 需要设置为 0。

                      除了有_id的时候 1 和 0 可以同时出现,其他时候要么都是 1,要么都是 0,不同 1 和 0 同时出现。

                        // 只返回age字段
                        db.accounts.find({}, {"age": 1, "_id": 0})
                        // 除了age 和 city其他字段都返回
                        db.accounts.find({}, {"age": 0, "city": 0})
                        // 这样会报错
                        db.accounts.find({}, {"age": 0, "city": 1})
                        
                        1
                        2
                        3
                        4
                        5
                        6
                        import pymongo
                        db = pymongo.MongoClient("mongodb://localhost:27017/")["ts"]
                        print(db.accounts.find({}, {"age": 1, "_id": 0}))
                        
                        1
                        2
                        3
                        // Make sure to add code blocks to your code group

                        # 插入

                          // 新增数据mongo会自动为每条数据添加一个_id
                          db.accounts.insert({"name": "new", "status": 1})
                          
                          1
                          2
                          import pymongo
                          db = pymongo.MongoClient("mongodb://localhost:27017/")["ts"]
                          print(db.accounts.insert({"name": "new", "status": 1}))
                          
                          1
                          2
                          3
                          // Make sure to add code blocks to your code group

                          # 更新

                          注意

                          如果不使用$set,会用新数据覆盖旧数据,一定要注意。

                          # 更新一条数据的指定字段

                            // 只会更新第一条数据
                            db.accounts.update({"name": "new"}, {"$set": {"status": 100}})
                            
                            1
                            2
                            import pymongo
                            db = pymongo.MongoClient("mongodb://localhost:27017/")["ts"]
                            db.accounts.update({"name": "new"}, {"$set": {"status": 100}})
                            
                            1
                            2
                            3
                            // Make sure to add code blocks to your code group

                            # 更新多条数据的指定字段

                              // 只会更新第一条数据
                              db.accounts.updateMany({"name": "new"}, {"$set": {"status": 200}})
                              
                              1
                              2
                              import pymongo
                              db = pymongo.MongoClient("mongodb://localhost:27017/")["ts"]
                              db.accounts.update_many({"name": "new"}, {"$set": {"status": 200}})
                              
                              1
                              2
                              3
                              // Make sure to add code blocks to your code group

                              # 删除

                              # 删除一条数据

                                db.accounts.remove({"name": "new"}, 1)
                                
                                1
                                import pymongo
                                db = pymongo.MongoClient("mongodb://localhost:27017/")["ts"]
                                db.accounts.delete_one({"name": "new"})
                                
                                1
                                2
                                3
                                // Make sure to add code blocks to your code group

                                # 删除多条数据

                                  db.accounts.remove({"name": "new"})
                                  
                                  1
                                  import pymongo
                                  db = pymongo.MongoClient("mongodb://localhost:27017/")["ts"]
                                  db.accounts.delete_many({"name": "new"})
                                  
                                  1
                                  2
                                  3
                                  // Make sure to add code blocks to your code group
                                  #MongoDB
                                  上次更新: 2023/08/08, 20:00:46
                                  聚合
                                  聚合

                                  ← 聚合 聚合→

                                  最近更新
                                  01
                                  攻略制作要点
                                  07-18
                                  02
                                  摄影主题拍摄
                                  07-18
                                  03
                                  延时摄影剧本
                                  07-18
                                  更多文章>
                                  Theme by Vdoing | Copyright © 2023-2024 Easton Yang | MIT License
                                  • 跟随系统
                                  • 浅色模式
                                  • 深色模式
                                  • 阅读模式