mongoose数据查询orandwhere等用法

Posted 浅夏晴空

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mongoose数据查询orandwhere等用法相关的知识,希望对你有一定的参考价值。

or

$or 条件指定参数;

//member = ["zhangsan", "lisi", "wangwu"];
let filter = {
  $or: [
    {docKey: "public"},
    {owner: "zhangsan"},
    {member: "lisi"}
  ]
}
db.getCollection(\'docs\').find(filter);
  1. 数据筛选or是或查询
  2. 满足下面的条件其中之一就可以查询出相关数据
  3. 如果数据库参数是数组,直接会从数组里面匹配是否包含相关数据 如上:member

and

$and 条件指定参数;

let filter = {
  $and: [
    {docKey: "public"},
    {owner: "zhangsan"}
  ]
}
db.getCollection(\'docs\').find(filter);

直译:

docKey == "public" && owner == "zhangsan"

需要满足枚举的两个条件才能筛选出相应数据;

and与or联合使用

let filter = {
  $or: [
          {
              docKey: "public"
          },
          {
              $and: [{docKey: "private"}, {$or:[{member: "zhangsan"}, {owner: "lisi"}]}]
          }
      ]
}
db.getCollection(\'docs\').find(filter);

直译:

docKey == "public" || (docKey == "private" && (member.indexOf("zhangsan")>-1 || owner=="lisi"))

where

let filter = {
  $or: [
          {
              docKey: "public"
          },
          {
              $where: function(){
                return this.docKey == "private" && (this.member.indexOf("zhangsan") > -1 || this.owner == "lisi");
              }
          }
      ]
}
db.getCollection(\'docs\').find(filter);

直译:

docKey == "public" || (docKey == "private" && (member.indexOf("zhangsan")>-1 || owner=="lisi"))

或者如下的写法

let filter = {
  $or: [
          {
              docKey: "public"
          },
          {
              $where: `this.docKey == "private" && (this.member.indexOf("zhangsan") > -1 || this.owner == "lisi")`
          }
      ]
}
db.getCollection(\'docs\').find(filter);

以上是关于mongoose数据查询orandwhere等用法的主要内容,如果未能解决你的问题,请参考以下文章

mongoose使用之查询篇

Mongoose 校验参数

[第16期] mongoDB 干货笔记(mongoose/增删改查/聚合/索引/连接/备份与恢复/监控等)

mongo 进阶之—— mongoose 认识

mongo 进阶之—— mongoose 认识

Mongoose:在添加 useNewUrlParse:true 等选项后,仍然收到来自 mongoose 模型 FindByIdAndUpdate() 的警告