zoukankan      html  css  js  c++  java
  • mongodb3.2系统性学习——4、find()操作

    find 操作语法展示:

     find()操作实例 :

    //连接数据库
    dbService = connect("localhost:27017"); 
    //选择插入集合
    db = dbService.getSiblingDB("jike");
    
    
    //创建bulk对象用于批量插入
    db.query_test.drop();
    var bulk = db.query_test.initializeUnorderedBulkOp();
    
    
    //测试数据
    var doc1 = {
                  name:"joe",
                  age:20
               }
    bulk.insert(doc1);
    
    
    
    var doc2 = {
                  name:"joe",
                  age:31
               }
    bulk.insert(doc2);
    
    var doc3 = {
                  name:"jack",
                  age:21
               }
    bulk.insert(doc3);
    
    var doc4 = {
                  name:"John",
                  age:null
               }
    bulk.insert(doc4);
    
    //执行插入操作
    bulk.execute()
    
    print("========find - 基本使用=======")
    /*
       db.集合名.find( query , fields , limit , skip)
    */
    var cursor = db.query_test.find(
                    {},                //查询条件
                    { _id:0,age:1},    //字段映射
                    2,                 //返回结果条数
                    1).sort({age:1});  //跳过文档条数   结果按照年龄升序排列
    printjson(cursor.toArray())
    
    
    var cursor = db.query_test.find(
                    {},                //查询条件
                    { _id:0,age:1}     //字段映射
                    ).limit(2).skip(1).sort({age:1}) 
    printjson(cursor.toArray())
    
    
    print("========find - $eq 比较操作符的使用=======")
    /*
     $eq  等值查询  匹配键值等于参数指定值的文档
     { <field>: { $eq: <value> } }
    */
    var cursor = db.query_test.find(
                    {
                       age: { $eq:20 }  //也可以写成  age:20
                       //age:20
                    } 
                );
    printjson(cursor.toArray())
    
    
    print("========find - $in 比较操作符的使用=======")
    /*
     $in  查询键值包含于参数数组中的文档,类似SQL中in
     { field: { $in: [<value1>, <value2>, ... <valueN> ] } }
    */
    var cursor = db.query_test.find(
                    {
                      age: { $in:[20,21] }  //age==20或age==21
                    } 
                );
    printjson(cursor.toArray())
    
    
    print("========find - $nin 比较操作符的使用=======")
    /*
     $nin  查询键值不存在或者键值不包含于参数数组中的文档
     { field: { $nin: [ <value1>, <value2> ... <valueN> ]} }
    */
    var cursor = db.query_test.find(
                    {
                      age: { $nin:[20,21] }   //age>21 && age<=31
                    } 
                );
    printjson(cursor.toArray())
    
    
    print("========find - $and 逻辑操作符的使用=======")
    /*
     $and  &&  且逻辑操作符    选择满足所有表达式的文档
     { $and: [ { <expression1> }, { <expression2> } , ... , { <expressionN> } ] }
     注意:1. and 操作符使用的是”短路运算“,即如果第一个表达式返回 false的话,不会再计算后面的表达式
          2. and 操作符有隐式和显式两种  隐式的可以使用 逗号 连接多个表达式
          3. 一般情况下隐式和显式两种方式是等价的,但有的时候只能显式使用$and
    */
    var cursor = db.query_test.find(
                    {
                      //$and: [ { age:{$gt:21}}, { age:{ $lte:31} } ]   //age>21 && age<=31
                      //age:{$gte:20,$lte:31}
                      $and: [ 
                              { $or:[ { age:19 },{ age:21 } ] },        //age=19或age=21
                              { $or:[ { name:"joe" },{ name:"jack" } ] }
                            ]  
                    } 
                );
    printjson(cursor.toArray())
    
    
    print("========find - $nor 逻辑操作符的使用=======")
    /*
     $nor   用于查询集合中不满足参数数组中列出的所有条件的文档
     { $nor: [ { <expression1> }, { <expression2> }, ...  { <expressionN> } ] }
    */
    var cursor = db.query_test.find(
                    {
                       $nor:[ 
                              { name:"joe"  },
                              { name:"jack" }  
                            ]  
                    });
    printjson(cursor.toArray())
    
    
    print("========find - $not/$gt/$lte 操作符的使用=======")
    /* 
       $not     对表达式取反     
       { field: { $not: { <operator-expression> } } }
    
       $gt  >   大于操作符      查询键值大于指定值的文档
       {field: {$gt: value} }
      
       $lte <=  小于等于操作符   查询键值不大于指定值的文档
       { field: { $lte: value} }
    */
    var cursor = db.query_test.find(
                     {  
                        age:{ $not: { $gt:22,$lte:30 } }   //age<=22 或  age>30
                     });                           
    printjson(cursor.toArray())
    
    
    print("========find - $exists 元素操作符的使用=======")
    /*
     $exists  查询存在(或不存在)指定字段的文档
     { field: { $exists: <boolean> } }
    */
    var cursor = db.query_test.find(
                    {
                       age: { $exists:true }   
                    } 
                );
    printjson(cursor.toArray())

     find() 数组查询:

    数组查询相关的操作符号:

      其中 $elemMatch 元素能当 查询条见  还能当 元素映射

    数组元素是普通元素

    //连接数据库
    dbService = connect("localhost:27017"); 
    //选择插入集合
    db = dbService.getSiblingDB("jike");
    
    //创建bulk对象用于批量插入
    db.query_array.drop();
    var bulk = db.query_array.initializeUnorderedBulkOp();
    
    //测试数据
    var doc1= 
            {   _id: 5, 
                name: "xiaoli", 
                age: 20,
                scores: [ 95, 98, 99 ] 
            }
    bulk.insert(doc1);
    
    var doc2= 
            {   _id: 6, 
                name: "xiaoqiang", 
                age: 22, 
                scores: [ 95, 99 ] 
            }
    
    bulk.insert(doc2);
    
    
    var doc3= 
            { 
              _id: 7, 
              name: "xiaoming", 
              item: 22, 
              scores: [ 99, 95, 98 ] 
            }
    bulk.insert(doc3);
    
    //执行插入操作
    bulk.execute()
    
    
    //测试查询
    print("========find--整个数组查询 ========")
    var cursor = db.query_array.find(
                            {
                                scores: [ 95, 98, 99 ] 
                            });
    printjson( cursor.toArray() );
    
    
    print("========find--数组查询(某一个数据元素)=======")
    var cursor = db.query_array.find(
                            {
                                scores: 95
                            });
    printjson( cursor.toArray() );
    
    
    var cursor = db.query_array.find( 
                            {
                                "scores.0": 95
                            });
    printjson( cursor.toArray() );
    
    print("========find--$all操作符的使用=======")
    /*
     用于查询数组中包含 $all数组参数指定的所有元素 的文档
     { <field>: { $all: [ <value1> , <value2> ... ] } } 
     注意:查询文档中数组元素的顺序可以和$all参数指定的数组元素的顺序不同
    */
    var cursor = db.query_array.find( 
                          {
                              scores:
                              {
                                 $all:[99,98]
                              }
                          });
    printjson( cursor.toArray() );
    
    
    print("========find--$elemMatch操作符的使用(多条件查询条件)=======")
    /*
      用于多条件查询  查询集合中文档的数组字段,至少有一个元素同时满足$eleMatch参数列出的所有条件 的文档
      { <field>: { $elemMatch: { <query1>, <query2>, ... } } }
      注意:如果不使用$eleMatch操作符,将返回 文档的数组字段任意元素的组合,满足所有条件的文档
    */
    var cursor = db.query_array.find( 
                            {
                               scores: 
                               { 
                                   $elemMatch: { $gt: 95, $lt: 99 } 
                               } 
                            });
    printjson( cursor.toArray() );
    
    
    var cursor = db.query_array.find( 
                            {
                                scores:
                                { 
                                   $gt: 95, $lt: 99 
                                }
                             } );
    printjson( cursor.toArray() );
    
    
    print("========find--$elemMatch操作符的使用(字段映射)=======")
    var cursor = db.query_array.find( 
                                {},        //查询条件
                                {
                                    scores://字段映射
                                     {
                                       $elemMatch:{ $gt:95, $lt:99 } 
                                    }
                                });
    printjson( cursor.toArray() );
    
    
    print("========find--$size操作符的使用=======")
    /*
     查询指定长度的数组
     { field: { $size: <number>} } 
     参数只能是一个确切的整数,不能和其它查询操作符一起使用  
    */
    var cursor = db.query_array.find( 
                            {  
                               scores: 
                               { 
                                   $size: 2
                               } 
                            });
    printjson( cursor.toArray() );
    
    print("========find--$slice操作符的使用=======")
    /*
     对数组元素做映射
     { array: {$slice: count } } 
     { array: {$slice: [skip,limit] } } 
    */
    var cursor = db.query_array.find( 
                          {},    //查询条件
                          {
                              scores://字段映射 
                              { 
                                  $slice: [1,2]
                              } 
                          });
    printjson( cursor.toArray() );
    
    
    print("========find--$操作符的使用=======")
    /*
     对数组元素做映射,只返回匹配的第一个元素
    db.collection.find( { <array>: <value> ... },
                        { "<array>.$": 1 } )
    db.collection.find( { <array.field>: <value> ...},
                        { "<array>.$": 1 } )
    需要说明的是,被限制的数组元素必须要出现在find函数第一个参数中,用于指明要查询的数组元素的条件
    */
    var cursor = db.query_array.find( 
                          { scores: {$gt:94} }, //查询条件
                          {
                              "scores.$":1      //返回满足查询条件的第一个数组元素
                          });
    printjson( cursor.toArray() );

    数组元素是 文档的时候:

    //连接数据库
    dbService = connect("localhost:27017"); 
    //选择插入集合
    db = dbService.getSiblingDB("jike");
    
    //创建bulk对象用于批量插入
    db.array_embedded.drop();
    var bulk = db.array_embedded.initializeUnorderedBulkOp();
    
    //测试数据
    var doc1= 
            {   _id: 1, 
                name: "xiaoli", 
                age: 20,
                scores: [ 
                          { 课程:"语文",成绩:90},
                          { 课程:"数学",成绩:95}
                        ] 
            }
    bulk.insert(doc1);
    
    var doc2= 
            {  _id: 2, 
                name: "xiaoqiang", 
                age: 22,
                scores: [ 
                          { 课程:"语文",成绩:92},
                          { 课程:"英语",成绩:90}
                        ] 
            }
    
    bulk.insert(doc2);
    
    //下面执行插入操作
    bulk.execute()
    
    //测试查询
    print("========find--数组查询(不使用数组索引) ========")
    var cursor = db.array_embedded.find({ 'scores.成绩':90 } );
    printjson( cursor.toArray() );
    
    
    print("========find--数组查询 (使用数组索引)========")
    var cursor = db.array_embedded.find( { 'scores.1.成绩': 90} );
    printjson( cursor.toArray() );
    
    
    
    print("========find--$elemMatch操作符(多条件查询条件)的使用========")
    var cursor = db.array_embedded.find( {
                                          scores: 
                                          { 
                                             $elemMatch: {"课程":"语文","成绩":90} 
                                           } 
                                         }
                                       );
    printjson( cursor.toArray() );

    $where 查询: 功能强大且灵活 可以把js表达式字符串或者函数作为查询语句的一部分,可以用this 或者 obj 来引用当前操作的文档 

    应当尽量避免使用,文档bson转为 js 对象才能运行,比常规的 要慢

    //连接数据库
    dbService = connect("localhost:27017"); 
    //选择插入集合
    db = dbService.getSiblingDB("jike");
    
    //创建bulk对象用于批量插入
    db.query_where.drop();
    var bulk = db.query_where.initializeUnorderedBulkOp();
    
    //测试数据
    var doc1 = { "apple":1, "banana": 6, "peach" : 4} 
    bulk.insert(doc1);
    
    var doc2 = {"apple":3, "banana": 3, "peach" : 4}        
    bulk.insert(doc2);
    
    //执行插入操作
    bulk.execute()
    
    
    print("========find--$where操作符的使用========")
    /*
      参数可以是JavaScript函数或JavaScript表达式的字符串
       { $where: function() { } }  
       { $where: "this.A == this.B"} 或 { $where: "obj.A == obj.B"}
    */
    var cursor = db.query_where.find(
                            {
                                $where:function() 
                                {
                                   for (var current in this) 
                                   {
    
                                      for (var other in this)
                                      {
                                           if (current != other && this[current] == this[other])    //查找文档中水果种类的数量是不是有一致的
                                               return true;
                                      }
                                   }
                                }
                            });
    printjson( cursor.toArray() );
    
    var cursor = db.query_where.find(
                            {
                                $where:"this.apple==1 && this.banana==6"
                            });
    printjson( cursor.toArray() );

    结果:
    [
        {
            "_id" : ObjectId("56c998011588ee87d0427795"),
            "apple" : 3,
            "banana" : 3,
            "peach" : 4
        }
    ]



    下面是很早之前学习使用的笔记

    一 创建数据库

     执行操作进入mongodb   使用参数模式   也可以使用 db.auth()来验证。

    root@timeless-HP-Pavilion-g4-Notebook-PC:/usr/local/apache243/htdocs# /usr/local/mongodb/mongo  -uroot -pxxxxx localhost:27017/admin

     下面是第一次创建新的数据库

    > use DEMO
    switched to db DEMO
    > db.user.insert({name:"zhaoxingzhuang",age:18,sex:"man",location:{province:"shandong",city:"jinan",road:"shandaroad-47"}})
    WriteResult({ "nInserted" : 1 })
    > db.user.find()  //全部查询
    { "_id" : ObjectId("54feea0a26be41dca9db0d23"), "name" : "zhaoxingzhuang", "age" : 18, "sex" : "man", "location" : { "province" : "shandong", "city" : "jinan", "road" : "shandaroad-47" } }
    > 

     继续执行插入操作 

    1、简单查询  find({field:"value"},{field:0或者1}) ,前边表示查询的条件  后边表示  查询的字段  0表示 不显示该字段  1表示只显示这个字段

    > db.user.insert({name:"wangping",age:26,sex:"woman",location:{city:"beijing",road:"zhongguonongyedaxue"}})
    WriteResult({ "nInserted" : 1 })
    > db.user.find()
    { "_id" : ObjectId("54feea0a26be41dca9db0d23"), "name" : "zhaoxingzhuang", "age" : 18, "sex" : "man", "location" : { "province" : "shandong", "city" : "jinan", "road" : "shandaroad-47" } }
    { "_id" : ObjectId("54feead226be41dca9db0d24"), "name" : "wangping", "age" : 26, "sex" : "woman", "location" : { "city" : "beijing", "road" : "zhongguonongyedaxue" } }
    > db.user.find({name:"wangping"})// 查询name="wangping"
    { "_id" : ObjectId("54feead226be41dca9db0d24"), "name" : "wangping", "age" : 26, "sex" : "woman", "location" : { "city" : "beijing", "road" : "zhongguonongyedaxue" } }
    
    //字段选取    类似 sql 语句中的 select age from XXX;
    > db.user.find({name:"wangping"},{age:0})     //表示不显示 age字段
    { "_id" : ObjectId("54feead226be41dca9db0d24"), "name" : "wangping", "sex" : "woman", "location" : { "city" : "beijing", "road" : "zhongguonongyedaxue" } }
    
    > db.user.find({name:"wangping"},{age:1})    // 表示只取  age字段
    { "_id" : ObjectId("54feead226be41dca9db0d24"), "age" : 26 }
    >

     2、条件查询 > $gt , < $lt ,<=   $lte ,>=  $gte。

    > db.user.find({age:{$gt:20}})   //查询年龄大于20岁的
    { "_id" : ObjectId("54feead226be41dca9db0d24"), "name" : "wangping", "age" : 26, "sex" : "woman", "location" : { "city" : "beijing", "road" : "zhongguonongyedaxue" } }
    > 

     3、$all操作只对数组有效(类似于 $in),    表示要查询的 $all:[1,2,5,6]    1256  必须全部在要查询的数组中 , 而$in 表示只要有一个就符合查询条件。

    > db.user.insert({name:"gaofei",age:24,grade:[1,2,5,6],location:{province:"shandong",city:"jiyang",road:"zuozhuangzhen"}})
    WriteResult({ "nInserted" : 1 })
    > db.user.find(grade:{$all:[1,2,5,6]})
    2015-03-10T21:19:20.164+0800 SyntaxError: Unexpected token :
    > db.user.find({grade:{$all:[1,2,5,6]}})    //$all  查询条件
    { "_id" : ObjectId("54feef3626be41dca9db0d25"), "name" : "gaofei", "age" : 24, "grade" : [ 1, 2, 5, 6 ], "location" : { "province" : "shandong", "city" : "jiyang", "road" : "zuozhuangzhen" } }
    > 

     $all   $in  只是用在数组上

    > db.user.find({name:{$all:[1,2,5,6]}})   //字段不是 数组  的情况
    > db.user.find({name:{$in:[1]}})
    > db.user.find({grade:{$in:[1]}})       //$in 使用查询
    { "_id" : ObjectId("54feef3626be41dca9db0d25"), "name" : "gaofei", "age" : 24, "grade" : [ 1, 2, 5, 6 ], "location" : { "province" : "shandong", "city" : "jiyang", "road" : "zuozhuangzhen" } }
    > 

    4、skip()   limit()  count()  sort()  使用

     其中  skip  跟 limit  使用 类似于   sql语句中的  select * from user limit 0,10;

    > db.user.find()    //按照添加顺序列出来
    { "_id" : ObjectId("54feea0a26be41dca9db0d23"), "name" : "zhaoxingzhuang", "age" : 18, "sex" : "man", "location" : { "province" : "shandong", "city" : "jinan", "road" : "shandaroad-47" } }
    { "_id" : ObjectId("54feead226be41dca9db0d24"), "name" : "wangping", "age" : 26, "sex" : "woman", "location" : { "city" : "beijing", "road" : "zhongguonongyedaxue" } }
    { "_id" : ObjectId("54feef3626be41dca9db0d25"), "name" : "gaofei", "age" : 24, "grade" : [ 1, 2, 5, 6 ], "location" : { "province" : "shandong", "city" : "jiyang", "road" : "zuozhuangzhen" } }
    //limit   从零开始 查询两条 
    > db.user.find().limit(2)
    { "_id" : ObjectId("54feea0a26be41dca9db0d23"), "name" : "zhaoxingzhuang", "age" : 18, "sex" : "man", "location" : { "province" : "shandong", "city" : "jinan", "road" : "shandaroad-47" } }
    { "_id" : ObjectId("54feead226be41dca9db0d24"), "name" : "wangping", "age" : 26, "sex" : "woman", "location" : { "city" : "beijing", "road" : "zhongguonongyedaxue" } }
    > db.user.skip(1).limit()
    2015-03-10T21:26:17.430+0800 TypeError: Property 'skip' of object DEMO.user is not a function
    > db.user.find().skip(1).limit()  //从第一条开始
    { "_id" : ObjectId("54feead226be41dca9db0d24"), "name" : "wangping", "age" : 26, "sex" : "woman", "location" : { "city" : "beijing", "road" : "zhongguonongyedaxue" } }
    { "_id" : ObjectId("54feef3626be41dca9db0d25"), "name" : "gaofei", "age" : 24, "grade" : [ 1, 2, 5, 6 ], "location" : { "province" : "shandong", "city" : "jiyang", "road" : "zuozhuangzhen" } }
    > db.user.count()   //统计数据总量
    3
    > db.user.find().sort(age:1)   // 即得要把排序的内容放在 {} 中
    2015-03-10T21:27:49.863+0800 SyntaxError: Unexpected token :
    > db.user.find().sort({age:1})
    { "_id" : ObjectId("54feea0a26be41dca9db0d23"), "name" : "zhaoxingzhuang", "age" : 18, "sex" : "man", "location" : { "province" : "shandong", "city" : "jinan", "road" : "shandaroad-47" } }
    { "_id" : ObjectId("54feef3626be41dca9db0d25"), "name" : "gaofei", "age" : 24, "grade" : [ 1, 2, 5, 6 ], "location" : { "province" : "shandong", "city" : "jiyang", "road" : "zuozhuangzhen" } }
    { "_id" : ObjectId("54feead226be41dca9db0d24"), "name" : "wangping", "age" : 26, "sex" : "woman", "location" : { "city" : "beijing", "road" : "zhongguonongyedaxue" } }
    > 

     4、$exists 字段存在使用

    > db.user.find({age:{$exists:1}})   //查询出存在字段age的记录
    { "_id" : ObjectId("54feea0a26be41dca9db0d23"), "name" : "zhaoxingzhuang", "age" : 18, "sex" : "man", "location" : { "province" : "shandong", "city" : "jinan", "road" : "shandaroad-47" } }
    { "_id" : ObjectId("54feead226be41dca9db0d24"), "name" : "wangping", "age" : 26, "sex" : "woman", "location" : { "city" : "beijing", "road" : "zhongguonongyedaxue" } }
    { "_id" : ObjectId("54feef3626be41dca9db0d25"), "name" : "gaofei", "age" : 24, "grade" : [ 1, 2, 5, 6 ], "location" : { "province" : "shandong", "city" : "jiyang", "road" : "zuozhuangzhen" } }
    > 

     5、$mod    取余数的操作   $mod[要除的数字,余数]

    > db.user.find({age:{$mod:[2,1]}})   //查询出除以二余数是一的记录
    { "_id" : ObjectId("54feead226be41dca9db0d24"), "name" : "wangping", "age" : 25, "sex" : "woman", "location" : { "city" : "beijing", "road" : "zhongguonongyedaxue" } }
    > 

     6、$in 表示在  $nin 表示除了

    > db.user.find({grade:{$in:[1,3,4]}})  //字段grade 中只要有 1,3,4中其中一个就可以。
    { "_id" : ObjectId("54feef3626be41dca9db0d25"), "name" : "gaofei", "age" : 24, "grade" : [ 1, 2, 5, 6 ], "location" : { "province" : "shandong", "city" : "jiyang", "road" : "zuozhuangzhen" } }
    > db.user.find({grade:{$in:[3,4]}}) //表示没有查询到
    > 

     $nin:[数组]  表示只要不再这里面的就符合查询条件  注意   没有这个字段的也符合条件

    > db.user.find({grade:{$nin:[3,4]}})
    { "_id" : ObjectId("54feead226be41dca9db0d24"), "name" : "wangping", "age" : 25, "sex" : "woman", "location" : { "city" : "beijing", "road" : "zhongguonongyedaxue" } }
    { "_id" : ObjectId("54feef3626be41dca9db0d25"), "name" : "gaofei", "age" : 24, "grade" : [ 1, 2, 5, 6 ], "location" : { "province" : "shandong", "city" : "jiyang", "road" : "zuozhuangzhen" } }
    > 

     7、复合查询  且   或   既不是也不是  

    > db.user.find({name:"wangping",age:25})     //表示且的关系
    { "_id" : ObjectId("54feead226be41dca9db0d24"), "name" : "wangping", "age" : 25, "sex" : "woman", "location" : { "city" : "beijing", "road" : "zhongguonongyedaxue" } }
    > db.user.find({$or:[{name:"wangping"},{age:26}]})   //或者关系
    { "_id" : ObjectId("54feead226be41dca9db0d24"), "name" : "wangping", "age" : 25, "sex" : "woman", "location" : { "city" : "beijing", "road" : "zhongguonongyedaxue" } }
    > db.user.find({$nor:[{name:"wangping"},{age:26}]})
    { "_id" : ObjectId("54feef3626be41dca9db0d25"), "name" : "gaofei", "age" : 24, "grade" : [ 1, 2, 5, 6 ], "location" : { "province" : "shandong", "city" : "jiyang", "road" : "zuozhuangzhen" } }

    8、$size  只是针对数组

    > db.user.find({grade:{$size:4}})
    { "_id" : ObjectId("54feef3626be41dca9db0d25"), "name" : "gaofei", "age" : 24, "grade" : [ 1, 2, 5, 6 ], "location" : { "province" : "shandong", "city" : "jiyang", "road" : "zuozhuangzhen" } }
    > 

     9、正则表达式

    > db.user.find({name:/.*w.*/i})
    { "_id" : ObjectId("54feead226be41dca9db0d24"), "name" : "wangping", "age" : 25, "sex" : "woman", "location" : { "city" : "beijing", "road" : "zhongguonongyedaxue" } }
    > 

     10、db.user.distinct()

    > db.user.distinct('name')
    [ "wangping", "gaofei" ]
    > 

    11、$eleMatch 

    The $elemMatch operator matches documents that contain an array field with at least one element that matches all the specified query criteria.

    意思是文档中 包含数组的字段中有一个或者多个符合条件就可以 

    { _id: 1, results: [ 82, 85, 88 ] }
    { _id: 2, results: [ 75, 88, 89 ] }
    db.scores.find(
       { results: { $elemMatch: { $gte: 80, $lt: 85 } } }
    )
    结果
    { "_id" : 1, "results" : [ 82, 85, 88 ] }

     另外还有种情况是 数组是嵌入的例如:

    { _id: 1, results: [ { product: "abc", score: 10 }, { product: "xyz", score: 5 } ] }
    { _id: 2, results: [ { product: "abc", score: 8 }, { product: "xyz", score: 7 } ] }
    { _id: 3, results: [ { product: "abc", score: 7 }, { product: "xyz", score: 8 } ] }

    //The following query matches only those documents
    where the results array contains at least one element with both product equal to "xyz" and score greater than or equal to 8.
    db.survey.find(
       { results: { $elemMatch: { product: "xyz", score: { $gte: 8 } } } }
    )

    Single Query Condition  一个查询条件的时候

    If you specify a single query predicate in the $elemMatch expression, $elemMatch is not necessary. 不是必须的

    For example, consider the following example where $elemMatch specifies only a single query predicate {product: "xyz" }:

    db.survey.find(
       { results: { $elemMatch: { product: "xyz" } } }
    )
    

    Since the $elemMatch only specifies a single condition, the $elemMatch expression is not necessary, and instead you can use the following query:

    db.survey.find(
       { "results.product": "xyz" }
    )

    12、游标使用

    MongoDB中find()函数返回一个游标,客户端通过对游标进行一些设置就能对查询结 果进行有效地控制,如可以限制查询得到的结果数量、跳过部分结果、或对结果集按任意键进行排序等!我们之前在Shell中进行操作,都是直接使用 find()函数,并没有使用其返回值,如:

    > for(var i=0;i<100;i++){ db.testcursor.insert({"num":i,"user":"user"+i}); }
    WriteResult({ "nInserted" : 1 })
    > db.testcursor.find()
    { "_id" : ObjectId("5502c26968baa7224b34c8ee"), "num" : 0, "user" : "user0" }
    { "_id" : ObjectId("5502c26968baa7224b34c8ef"), "num" : 1, "user" : "user1" }
    { "_id" : ObjectId("5502c26968baa7224b34c8f0"), "num" : 2, "user" : "user2" }
    { "_id" : ObjectId("5502c26968baa7224b34c8f1"), "num" : 3, "user" : "user3" }
    { "_id" : ObjectId("5502c26968baa7224b34c8f2"), "num" : 4, "user" : "user4" }
    { "_id" : ObjectId("5502c26968baa7224b34c8f3"), "num" : 5, "user" : "user5" }
    { "_id" : ObjectId("5502c26968baa7224b34c8f4"), "num" : 6, "user" : "user6" }
    { "_id" : ObjectId("5502c26968baa7224b34c8f5"), "num" : 7, "user" : "user7" }
    { "_id" : ObjectId("5502c26968baa7224b34c8f6"), "num" : 8, "user" : "user8" }
    { "_id" : ObjectId("5502c26968baa7224b34c8f7"), "num" : 9, "user" : "user9" }
    { "_id" : ObjectId("5502c26968baa7224b34c8f8"), "num" : 10, "user" : "user10" }
    { "_id" : ObjectId("5502c26968baa7224b34c8f9"), "num" : 11, "user" : "user11" }
    { "_id" : ObjectId("5502c26968baa7224b34c8fa"), "num" : 12, "user" : "user12" }
    { "_id" : ObjectId("5502c26968baa7224b34c8fb"), "num" : 13, "user" : "user13" }
    { "_id" : ObjectId("5502c26968baa7224b34c8fc"), "num" : 14, "user" : "user14" }
    { "_id" : ObjectId("5502c26968baa7224b34c8fd"), "num" : 15, "user" : "user15" }
    { "_id" : ObjectId("5502c26968baa7224b34c8fe"), "num" : 16, "user" : "user16" }
    { "_id" : ObjectId("5502c26968baa7224b34c8ff"), "num" : 17, "user" : "user17" }
    { "_id" : ObjectId("5502c26968baa7224b34c900"), "num" : 18, "user" : "user18" }
    { "_id" : ObjectId("5502c26968baa7224b34c901"), "num" : 19, "user" : "user19" }
    Type "it" for more

     我们先通过javascript脚本向集合中填充100条文档,然后直接调用find函数。其会自动递归find返回的游标,将前20条数据展示在shell中。如果我们通过变量保留find函数的返回值,其不会自动进行遍历显示操作:

    > var cursor = db.coll.find();
     

      这样做,实际发生的是,调用完find后,此时Shell并不会去真正地访问数据库, 而是等 待开始要求获得结果的时候才向数据库发送查询请求!我们此时可以对这个游标进行各种设置,然后调用游标的hashNext()或next()方法,这样就 会真正访问数据库,这是一个懒加载的过程。如下

    > var cursor=db.testcursor.find();
    > while(cursor.hasNext()){
    ... var perdata=cursor.next();
    ... print("编号"+perdata.num);
    ... print("user"+perdata.user);
    ... }
    编号0
    useruser0
    编号1
    useruser1
    编号2
    useruser2
    编号3
    useruser3
    编号4
    useruser4
    编号5

    上述代码中,当调用cursor.hasNext()时,查询被发往数据库,默认会返回前 100条文档或者前4M的数据(两者之中较小的),这样下次next或hasNext都是本地调用了!当这组数据被遍历完毕,hasNext会导致再次去 访问数据库,直到所有结果被返回!

     13、null值查询,当使用 db.testNull.find({"y":null}) 查找字段时包含字段不存在的和值为null的。所以应该使用 {"xxx":{$type:10}}作为查询条件来查找字段值为null的,而{"xxx":{$exists:0}}表示用来查找字段不存在的。  查看 字段 类型值

    > db.testNull.insert({"x":1,"y":"String"})
    WriteResult({ "nInserted" : 1 })
    > db.testNull.insert({"x":1,"y":null})//插入null
    WriteResult({ "nInserted" : 1 })
    > db.testNull.insert({"x":1})    //不存在y字段
    WriteResult({ "nInserted" : 1 })
    > db.testNull.find({"y":null})     //查询出来的可能为null的也可能为 字段不存在的
    { "_id" : ObjectId("5502c70868baa7224b34c953"), "x" : 1, "y" : null }
    { "_id" : ObjectId("5502c70e68baa7224b34c954"), "x" : 1 }
    > db.testNull.find({"y":{$type:10}})   //查询出来的是字段存在但是数值为 null的    Double  1       
    { "_id" : ObjectId("5502c70868baa7224b34c953"), "x" : 1, "y" : null }
    > db.testNull.find({"y":{$exists:0}})  //查询出来的是字段不存在的
    { "_id" : ObjectId("5502c70e68baa7224b34c954"), "x" : 1 }

    14、$slice  通过$slice返回数组中的部分数据。"$slice":2表示数组中的前两个元素。  负数 截取后边几条数据   [x,y]   x表示从什么地方开始   y 表示数量    [-1,1] 表示从-1位置截取向后截取1个

    > db.testSlice.insert({"person":[{"name":"zhaoxingzhuang"},{"name":"libai"},{"name":"dufu"}]})
    WriteResult({ "nInserted" : 1 })
    > db.testSlice.find({},{"person":{$slice:1}})   //表示从 testSlice中取出person中的一条记录    前提是person必须是数组
    { "_id" : ObjectId("5502cc8a68baa7224b34c955"), "person" : [ { "name" : "zhaoxingzhuang" } ] }
    > 

  • 相关阅读:
    linux redis 安装和链接,,,
    ppt转化pdf
    跨服务器 同步数据
    字典表相关
    代码重构,空间换时间,dictionary 不要用object ,需明确指定类型
    stringbuilder for test performance 性能 update 性能
    nvarchar 和varchar 在len下一致,datalength下nvarchar翻倍
    android GradLayout实现计算器
    屏幕录制GIF动画工具
    android SharedPreferences 简单的数据存储
  • 原文地址:https://www.cnblogs.com/timelesszhuang/p/4328478.html
Copyright © 2011-2022 走看看