查询指令
假设我们需要查询进度大于 30% 的待办事项,那么传入对象表示全等匹配的方式就无法满足了,这时就需要用到查询指令。数据库 API 提供了大于、小于等多种查询指令,这些指令都暴露在
db.command
对象上。例如查询进度大于 30% 的待办事项:const cloudbase = require("@cloudbase/js-sdk");const app = cloudbase.init({env: "xxxx"});// 1. 获取数据库引用var db = app.database();const _ = db.command;db.collection("todos").where({// gt 方法用于指定一个 "大于" 条件,此处 _.gt(30) 是一个 "大于 30" 的条件progress: _.gt(30)}).get().then((res) => {console.log(res.data);});
// 1. 获取数据库引用const db = wx.cloud.database();const _ = db.command;db.collection("todos").where({// gt 方法用于指定一个 "大于" 条件,此处 _.gt(30) 是一个 "大于 30" 的条件progress: _.gt(30)}).get().then((res) => {console.log(res.data);});
const cloudbase = require("@cloudbase/node-sdk");const app = cloudbase.init({});// 1. 获取数据库引用const db = app.database();const _ = db.command;exports.main = async (event, context) => {const res = await db.collection("todos").where({// gt 方法用于指定一个 "大于" 条件,此处 _.gt(30) 是一个 "大于 30" 的条件progress: _.gt(30)}).get();return {res};};
API 提供了以下查询指令:
查询指令 | 说明 |
eq | 等于 |
neq | 不等于 |
lt | 小于 |
lte | 小于或等于 |
gt | 大于 |
gte | 大于或等于 |
in | 字段值在给定数组中 |
nin | 字段值不在给定数组中 |
具体的查询指令 API 文档可参考各 SDK API。
逻辑指令
除了指定一个字段满足一个条件之外,我们还可以通过指定一个字段需同时满足多个条件,例如我们 查询进度小于或等于 50% 或 颜色为白色或黄色 的待办事项:
const cloudbase = require("@cloudbase/js-sdk");const app = cloudbase.init({env: "xxxx"});// 1. 获取数据库引用var db = app.database();const _ = db.command;db.collection("todos").where(_.or([{progress: _.lte(50)},{style: {color: _.in(["white", "yellow"])}}])).get().then((res) => {console.log(res.data);});
// 1. 获取数据库引用const db = wx.cloud.database();const _ = db.command;db.collection("todos").where(_.or([{progress: _.lte(50)},{style: {color: _.in(["white", "yellow"])}}])).get().then((res) => {console.log(res.data);});
const cloudbase = require('@cloudbase/node-sdk');const app = cloudbase.init({})// 1. 获取数据库引用const db = app.database()const _ = db.commandexports.main = async (event, context) => {const res = await db.collection('todos').where(_.or([{progress: _.lte(50)},{style: {color: _.in(['white', 'yellow'])}}])).get()return {res}}
具体的查询指令 API 文档可参考各 SDK API。