unicloud云开发进阶6-初识JQL语法建议的where查询

251 阅读1分钟

JQL语法

原本的写法

新建一个demo1页面,在这里连接数据库获取数据,(先把read属性改成true)

<script>
  const db=uniCloud.database()
  export default {
    data() {
      return {
        
      }
    },
    onLoad() {
      this.getData()
    },
    methods: {
      getData(){
        db.collection("users").where({
          age:30
        }).get().then(res=>{
          console.log(res);
        })
      }
    }
  }
</script>

如果是查找大于30的

<script>
  const db=uniCloud.database();
  const dbCmd=db.command;
  export default {
    data() {
      return {
        
      }
    },
    onLoad() {
      this.getData()
    },
    methods: {
      getData(){
        db.collection("users").where({
          age:dbCmd.gt(30)
        }).get().then(res=>{
          console.log(res);
        })
      }
    }
  }
</script>

JQL语法

上面是之前的传统写法,可读性差,比如这个联表查询

const db = uniCloud.database()
const dbCmd = db.command
const $ = dbCmd.aggregate
let res = await db.collection('orders').aggregate()
.lookup({
  from: 'books',
  let: {
    order_book: '$book',
    order_quantity: '$quantity'
  },
  pipeline: $.pipeline()
    .match(dbCmd.expr($.and([
      $.eq(['$title', '$$order_book']),
      $.gte(['$stock', '$$order_quantity'])
    ])))
    .project({
      _id: 0,
      title: 1,
      author: 1,
      stock: 1
    })
    .done(),
  as: 'bookList',
})
.end()

使用JQL的写法 直接在where里面写表达式

    methods: {
      getData(){
        db.collection("users").where("age==30").get().then(res=>{
          console.log(res);
        })
      }
    }