mongoose学习笔记(三)之增加和查找具体

上一篇笔记仅记录了简单的增删改查,这篇笔记将介绍一些增删改查中更具体的一些方法。

先定义model

var blogSchema = new Schema({
    title:  Number,
    author: String,
    body:   String
  });
 
  var Blog = mongoose.model('Blog', blogSchema);

定义一个数组

var blogs=new Array();
  for(i=0;i<200000;i++){
    let blog=new Blog({
      title:  i,
      author: "author",
      body: "caocaocao"
    })
    blogs.push(blog);
  }

增加多条数据

  • insertMany
Blog.insertMany(blogs,function(err){      
    console.log(err);
  });
  • create
Blog.create(blogs, function (err, res) {
      if (!err) {
             console.log('ok');
       }
 })

高级查找

  • $gt$lt简述
     “$lt"(小于)”,"$lte"(小于等于),"$gt"(大于),"$gte"(大于等于),"$ne"(不等于),"$in"(可单值和多个值的匹配),"$or"(查询多个键值的任意给定值),"$exists"(表示是否存在的意思)"$all"。

$gt(>)、$lt(<)、$lte(<=)、$gte(>=)操作符相当于大于、小于、大于等于、小于等于,具体使用方法如下:

Blog.find({"age":{"$gt":18,"$lt":60}},function(error,docs){
   //查询所有age大于18小于60的数据
});

Blog.find({"age":{"$gte":20,"$lte":50}},function(error,docs){
   //查询20≤age≤50的所有数据
});

$ne(!=)操作符的含义相当于不等于、不包含,查询时我们可通过它进行条件判定,具体使用方法如下:

Blog.find({name:{$ne:"tom"},age:{$gte:18}},function(error,docs){
  //查询name不等于tom、age>=18的所有数据
});

$in相当于包含、等于,查询时查找包含于指定字段条件的数据。具体使用方法如下:

Blog.find({ age:{ $in: 20}},function(error,docs){
   //查询age等于20的所有数据
});

Blog.find({ age:{$in:[20,30]}},function(error,docs){
  //可以把多个值组织成一个数组
}); 

Blog.find({ age: {$in:[24,25,27]}},function(error,docs){
    //查询age为24、25、27的所有数据
});

$or操作符,可以查询多个键值的任意给定值,只要满足其中一个就可返回,用于存在多个条件判定的情况下使用,如下示例:

Blog.find({"$or":[{"name":"yaya"},{"age":28}]},function(error,docs){
  //查询name为yaya或age为28的全部文档
});

$exists操作符,可用于判断某些关键字段是否存在来进行条件查询。如下示例:

Blog.find({name: {$exists: true}},function(error,docs){
  //查询所有存在name属性的文档
});
Blog.find({telephone: {$exists: false}},function(error,docs){
  //查询所有不存在telephone属性的文档
})
  • Model 的方法中不包含回调函数查询

//下面两个查询等效

// With a JSON doc
Person.
  find({
    occupation: /host/,    //正则表达式
    'name.last': 'Ghost',   //具体字段
    age: { $gt: 17, $lt: 66 },  //17
    likes: { $in: ['vaporizing', 'talking'] }   //包含这两个词
  }).
  limit(10).                 //限制10条内容
  sort({ occupation: -1 }).   //降序排列
  select({ name: 1, occupation: 1 }).    //只要name和occupation两个字段
  exec(callback(err,res));          //执行回调函数

// 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);

你可能感兴趣的:(mongoDb,mongoose)