zoukankan      html  css  js  c++  java
  • 集合

    Person. find({ occupation: /host/, 'name.last': 'Ghost', age: { $gt: 17, $lt: 66 }, likes: { $in: ['vaporizing', 'talking'] } }). limit(10). sort({ occupation: -1 }). select({ name: 1, occupation: 1 }). exec(callback); // Using query builder Person. find({ occupation: /host/ }). where('name.last').equals('Ghost'). where('age').gt(17).lt(66). where('likes').in(['vaporizing', 'talking']). limit(10). sort('-occupation'). select('name occupation'). exec(callback);

    https://docs.mongodb.org/manual/reference/operator/query/regex/ 

    { description: { $regex: /S/ } } 
    { results: { $elemMatch: { $gte: 80, $lt: 85 } } }

    https://docs.mongodb.org/manual/reference/sql-aggregation-comparison/

    db.orders.aggregate( [
    其中数组字段不为空
    ME.find({pictures: {$not: {$size: 0}}})  &&
    ME.find({'pictures.0': {$exists: 1}});
     

    find({"x":{"$in":[1,2,3]}})
    find({"$or":[{"s":"ss"},{"x":"xx"}]})
    {"id_num":{"$mod":[5,1]}}
    {"id_num":{"$not":{"$mod":[5,1]}}}
    不存在or null
    {"z":{"$in":[null],"$exists":true}}
    {"name":/joe/i}

    var criteria = {title : 'emtity_demo_title'}; // 查询条件
    var fields   = {title : 1, content : 1, time : 1}; // 待返回的字段
    var options  = {};
    mongooseModel.find(criteria, fields, options, function(error, result){

    var conditions = {username: 'emtity_demo_username'};

    mongooseModel.remove(conditions, function(error){
    Model.count(conditions, callback);
    Model.find({ 'csser.com': 5 }, function (err, docs)
    Model.findById(obj._id, function (err, doc){
    Model.count(conditions, callback);
    .where('age').gte(25)
    .where('tags').in(['movie', 'music', 'art'])
    .select('name', 'age', 'tags')
    .skip(20)
    .limit(10)
    .asc('age')
    .slaveOk()
    .hint({ age: 1, name: 1 })
    .run(callback);

    Model.$where


    var conditions = {username : 'model_demo_username'};
    var update     = {$set : {age : 27, title : 'model_demo_title_update'}};
    var options    = {upsert : true};
    mongooseModel.update(conditions, update, options, function(error){
        if(error) {
            console.log(error);
        } else {
            console.log('update ok!');
        }

    });


    db.test.update({_id:"b"}, {$inc:{n:1}}, true, false) //
    upsert=True, multi=True

    混合类型因为没有特定约束,因此可以任意修改,一旦修改了原型,则必须调用markModified()

        person.anything = {x:[3,4,{y:'change'}]}
        person.markModified('anything');//传入anything,表示该属性类型发生变化
        person.save();
     if (err) {
            console.log('保存失败')
            return;
        }



    Model.update({"_id" : { $in : ids }},{"foo":"bar"},{multi:true},function(){ console.log("I have enjoyed crippling your server."); });
     db.post.update({count:100},{"$inc":{count:10}},true); //(upsert 的名字也很有趣是个混合体:update+insert)
    db.inventory.save( { type: "book", item: "notebook", qty: 40 } )
    UserModel.update({ nick: act.nick }, { $set: lfmuser }, { upsert: true }, function(){});
    var ContactSchema = new Schema({
        phone: { type: String, index: { unique: true, dropDups: true } },
        status: { type: String, lowercase: true, trim: true, default: 'on' }
    });

    var update = {name: 'updated item2', value: 'two updated'};
    Person.update({'items.id': 2}, {'$set': {'items.$': update}}, function(err) { ...
    {'$set': {'items.$.name': update.name , 'items.$.value': update.value}}

    Book.findOne({isbn: req.params.isbn}, function (err, book){
         if (err) {
            res.json({"success":false});
         } else {
            //update fields
            for (var field in Book.schema.paths) {
               if ((field !== '_id') && (field !== '__v')) {
                  if (req.body[field] !== undefined) {
                     book[field] = req.body[field];
                  }  
               }  
            }  
            book.save();
         }
      });

    db.foo.update({"array.value" : 22}, {"$set" : {"array.$.text" : "blah"}})
    "array" : [{"text" : "foo", "value" : 11},{"text" : "foo", "value" : 22},{"text" : "foobar", "value" : 33}]
    "array" : [{"text" : "foo", "value" : 11},{"text" : "foobar", "value" : 33},{"text" : "blah", "value" : 22}]

     

    db.collection.update(query, update, options)

    改变一个在集合中已经存在的文档或文档数组。默认的,update()方法更新一个独立的文档。如果multi选项被设置为true(真),这个方法更新匹配条件的所有文档。

    方法格式:

    db.collection.update(
       <query>,
       <update>,
       { upsert: <boolean>, multi: <boolean> }
    )
    
    参数类型描述
    query 文档 选择器,与find()中的用法一样。
    update 文档 改变
    upsert 文档、布尔 可选。默认为false。如果为true,则表示“如果文档不存在,则创建集合。”
    multi 文档、布尔 可选。默认为false。如果为true,则表示“更改所有符合条件的项目。”

    update参数说明

    参考

    NameDescription
    $inc 通过指定的数值自增长某个字段的值。
    $rename 重命名一个字段
    $setOnInsert 当文档在upsert创建期间,设置一个字段的值。对于已经存在的项目的更新不起作用。
    $set 在一个已经存在的文档的字段值。
    $unset 从一个文档中移除一个字段。

    示例

    db.products.update( { sku: "abc123" },
                        { $inc: { quantity: 5 } } )
    

    增长sky为abc123的文档的quantity字段的值5次。(如:原为1,增长后为6)

    数组操作

    NameDescription
    $ 作为一个占位符来更新一次update操作中的第一个符合条件的元素。
    $addToSet 仅当它们在集合中不存在的时候,添加元素到一个已经存在的数组。
    $pop 移除一个数组中第一个或最后一个元素。
    $pullAll 从一个数组中移除所有元素。
    $pull 从一个数组中移除匹配的元素。
    $pushAll 不建议使用. 添加所有元素。
    $push 添加一个元素。

    $push简单说明

    格式

    db.collection.update( <query>,
                          { $push: { <field>: <value> } }
                        )
    

    示例

    db.students.update(
                        { name: "joe" },
                        { $push: { scores: 89 } }
                      )
    

    更改器

    NameDescription
    $each $push和$addToSet的更改操作,为一个数组更新多个附加的项目。
    $slice $push的更改操作来限制被更新数组的尺寸。
    $sort $push的更改操作,为一个已经存在的数组排序。

    插入多条测试数据
    > for(i=1;i<=1000;i++){
    ... db.blog.insert({"title":i,"content":"mongodb测试文章。","name":"刘"+i});                                                      
    ... }

    db.blog.list.find().limit(10).forEach(function(data){print("title:"+data.title);})   循环forEach 用法

    db.blog.findOne();  取一条数据

    db.blog.find();取多条数据
    db.blog.remove(); 删除数据集 
    db.blog.drop();删除表

    删除一个数据库: 
    1.use dbname 
    2.db.dropDatabase()


    ======================================查询操作=============================
    db.blog.find() 相当于select * from blog 
    db.blog.find({"age":27}) 相当于select * from blog where age='27'
    db.blog.find({"age":27,"name":"xing"}) 相当于select * from blog where age='27' and name="xing"
    db.blog.find({},{"name":1}) select name from blog ,如果name:0则是不显示name字段
    db.blog.find().limit(1) 相当于select * from blog limit 1

    db.blog.find().sort({_id:-1}).limit(1)相当于select * from blog order by _id desc limit 1
    db.blog.find().skip(10).limit(20) 相当于select * from blog limit 10,20
    skip用的时候,一定要注意要是数量多的话skip就会变的很慢,所有的数据库都存在此问题,可以不用skip进行分页,用最后一条记录做为条件
    db.blog.find({"age":{"$gte":18,"$lte":30}})     select * from blog  where age>=27 and age<=50
    $gt   >
    $gte  >=
    $lt   <
    $lte  <=
    $ne   !=
    $in : in 
    $nin: not in 
    $all: all 
    $not: 反匹配

    查询 creation_date > '2010-01-01' and creation_date <= '2010-12-31' 的数据 
    db.users.find({creation_date:{$gt:new Date(2010,0,1), $lte:new Date(2010,11,31)});

    db.blog.find().sort({_id:-1})  相当于select * from blog  order by _id desc  按_id倒序取数据  1为正序,多个条件用,号分开如{name:1,age:-1}
    db.blog.find({"_id":{"$in",[12,3,100]}})  相当于select * from blog where _id in (12,3,100)
    db.blog.find({"_id":{"$nin",[12,3,100]}})  相当于select * from blog where _id not in (12,3,100)
    db.blog.find({"$or":[{"age":16},{"name":"xing"}]}) 相当于select * from blog where age = 16 or name = 'xing'
    db.blog.find({"id_num":{"$mod":[5,1]}}) 取的是id_num mod 5 = 1 的字段,如id_num=1,6,11,16
    db.blog.find({"id_num":{"$not":{"$mod":[5,1]}}}) 取的是id_num mod 5 != 1 的字段,如除了id_num=1,6,11,16等所有字段,多于正则一起用

    $exists判断字段是否存在

    db.blog.find({ a : { $exists : true }}); // 如果存在元素a,就返回
    db.blog.find({ a : { $exists : false }}); // 如果不存在元素a,就返回


    $type判断字段类型 
    查询所有name字段是字符类型的 
    db.users.find({name: {$type: 2}}); 
    查询所有age字段是整型的 
    db.users.find({age: {$type: 16}}); 


    db.blog.find({"z":null}) 返回没有z字段的所有记录
    db.blog.find({"name":/^joe/i}) 查找name=joe的所有记录,不区分大小写

    db.blog.distinct('content')  查指定的列,并去重


    查询数组
    db.blog.find({"fruit":{"$all":["苹果","桃子","梨"]}})   fruit中必需有数组中的每一个才符合结果
    db.blog.find({"fruit":{"$size":3}})  fruit数组长度为3的符合结果
    db.blog.find({"$push":{"fruit":"桔子"}})相当于db.blog.find({"$push":{"fruit":"桔子"},"$inc":{"size":1}})
    $slice 可以按偏移量返回记录,针对数组。如{"$slice":10}返回前10条,{"$slice":{[23,10]}}从24条取10条
    如果对象有一个元素是数组,那么$elemMatch可以匹配内数组内的元素

    db.people.find({"name.first":"joe","name.last":"schmoe"}) 子查询如:{"id":34,"name":{"first":"joe","last":"schmoe"}}

    db.blog.find({"comments":{"$elemMatch":{"author":"joe","score":{"$gte":5}}}}) 查joe发表的5分以上的评论,注意comments为二维数组
    $where 在走投无路的时候可以用,但它的效率是很低的。


    游标用法
    cursor.hasNext()检查是否有后续结果存在,然后用cursor.next()将其获得。
    >while(cursor.hasNext()){
       var obj = cursor.next();
       //do same
    }

    http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-ConditionalOperators%3A%3C%2C%3C%3D%2C%3E%2C%3E%3D 手册

    > use blog
    > db.blog.insert({"title":"华夏之星的博客","content":"mongodb测试文章。"});
    > db.blog.find();
    { "_id" : ObjectId("4e29fd262ed6910732fa61df"), "title" : "华夏之星的博客", "content" : "mongodb测试文章。" }
    > db.blog.update({title:"华夏之星的博客"},{"author":"星星","content":"测试更新"});
    > db.blog.find();
    { "_id" : ObjectId("4e29fd262ed6910732fa61df"), "author" : "星星", "content" : "测试更新" }


     db.blog.insert不带括号则显示源码
    db.blog.insert();插入
    db.blog.update();更新

    > db.blog.update({title:"华夏之星的博客"},{"author":"星星","content":"测试更新"});

    update默认情况下只能对符合条件的第一个文档执行操作,要使所有的匹配的文档都得到更新,可以设置第四个参数为 true

    > db.blog.update({title:"华夏之星的博客"},{"author":"星星","content":"测试更新"},false,true);

    > db.runCommand({getLastError:1}) 可以查看更新了几条信息,n就是条数

     备份blog数据库到/soft目录
    /usr/local/webserver/mongodb/bin/mongodump -d blog -o /soft

    还原数据库

    /usr/local/webserver/mongodb/bin/mongorestore -d blog -c blog   /soft/blog/blog.bson

     
    导出数据库(备份出来的数据是二进制的,已经经过压缩。)
    /usr/local/webserver/mongodb/bin/mongodump -h 127.0.0.1 -port 27017 -d demo -o /tmp/demo
    导入数据
    /usr/local/webserver/mongodb/bin/mongorestore -h 127.0.0.1  -port 27017 --directoryperdb /tmp/demo

     

    5) $all
    $all和$in类似,但是他需要匹配条件内所有的值:
    如有一个对象:
    { a: [ 1, 2, 3 ] }

    下面这个条件是可以匹配的:

    db.things.find( { a: { $all: [ 2, 3 ] } } );

    但是下面这个条件就不行了:

    db.things.find( { a: { $all: [ 2, 3, 4 ] } } );
    6) $size
    $size是匹配数组内的元素数量的,如有一个对象:{a:["foo"]},他只有一个元素:
    下面的语句就可以匹配:
    db.things.find( { a : { $size: 1 } } );

    官网上说不能用来匹配一个范围内的元素,如果想找$size<5之类的,他们建议创建一个字段来保存元素的数量。

    8) $type

    $type 基于 bson type来匹配一个元素的类型,像是按照类型ID来匹配,不过我没找到bson类型和id对照表。

    db.things.find( { a : { $type : 2 } } ); // matches if a is a string
    db.things.find( { a : { $type : 16 } } ); // matches if a is an int

    9)正则表达式
    mongo支持正则表达式,如:
    db.customers.find( { name : /acme.*corp/i } ); // 后面的i的意思是区分大小写
    10) 查询数据内的值
    下面的查询是查询colors内red的记录,如果colors元素是一个数据,数据库将遍历这个数组的元素来查询。
    db.things.find( { colors : "red" } );

    11) $elemMatch
    如果对象有一个元素是数组,那么$elemMatch可以匹配内数组内的元素:
    > t.find( { x : { $elemMatch : { a : 1, b : { $gt : 1 } } } } ) 
    { "_id" : ObjectId("4b5783300334000000000aa9"), 
    "x" : [ { "a" : 1, "b" : 3 }, 7, { "b" : 99 }, { "a" : 11 } ]
    }
    $elemMatch : { a : 1, b : { $gt : 1 } } 所有的条件都要匹配上才行。

    注意,上面的语句和下面是不一样的。

    > t.find( { "x.a" : 1, "x.b" : { $gt : 1 } } )

    $elemMatch是匹配{ "a" : 1, "b" : 3 },而后面一句是匹配{ "b" : 99 }, { "a" : 11 } 
    12) 查询嵌入对象的值
    db.postings.find( { "author.name" : "joe" } );

    注意用法是author.name,用一个点就行了。更详细的可以看这个链接: dot notation

    举个例子:

    > db.blog.save({ title : "My First Post", author: {name : "Jane", id : 1}})

    如果我们要查询 authors name 是Jane的, 我们可以这样:

    > db.blog.findOne({"author.name" : "Jane"})
    http://www.cnblogs.com/sitemanager/archive/2013/12/16/3476910.html
    http://www.cnblogs.com/yuechaotian/archive/2013/02/04/2890266.html
  • 相关阅读:
    SOLO: 按位置分割对象
    支付宝架构
    h264和h265多维度区别
    机器学习图解
    机器视觉系统性能
    APA自动泊车系统
    智能驾驶测距估计
    结构感知图像修复:ICCV2019论文解析
    Lambda表达式
    转:利用 T-sql 的从句 for xml path('') 实现多行合并到一行, 并带有分隔符
  • 原文地址:https://www.cnblogs.com/jayruan/p/5140977.html
Copyright © 2011-2022 走看看