uni-app学习笔记之数据库常用操作

日期进行比较操作

//可以使用聚合操作符将日期进行转化,比如以下示例查询所有time字段在2020-02-02以后的记录
use strict;
const db = uniCloud.database()
exports.main = async (event, context) => {
          
   
    const dbCmd = db.command
    const $ = dbCmd.aggregate
    let res = await db.collection(unicloud-test).where(dbCmd.expr(
        $.gte([$time,$.dateFromString({
          
   
            dateString: new Date(2020-02-02).toISOString()
        })])
    )).get()
    return res
};

GEO地理位置

注意:如果需要对类型为地理位置的字段进行搜索,一定要建立地理位置索引。

GEO数据类型 Point 用于表示地理位置点,用经纬度唯一标记一个点,这是一个特殊的数据存储类型。

Point(longitude: number, latitude: number)

示例:

new db.Geo.Point(longitude, latitude)

GEO操作符 geoNear 按从近到远的顺序,找出字段值在给定点的附近的记录。

//签名:

db.command.geoNear(options: IOptions)

interface IOptions {
          
   
  geometry: Point // 点的地理位置
  maxDistance?: number // 选填,最大距离,米为单位
  minDistance?: number // 选填,最小距离,米为单位
}

//示例:

let res = await db.collection(user).where({
          
   
  location: db.command.geoNear({
          
   
    geometry: new db.Geo.Point(lngA, latA),
    maxDistance: 1000,
    minDistance: 0
  })
}).get()

如筛选出内存大于 4g 小于 32g 的计算机商品

//流式写法:

const dbCmd = db.command
db.collection(goods).where({
          
   
  category: computer,
  type: {
          
   
    memory: dbCmd.gt(4).and(dbCmd.lt(32))
  }
})

//前置写法:

const dbCmd = db.command
db.collection(goods).where({
          
   
  category: computer,
  type: {
          
   
    memory: dbCmd.and(dbCmd.gt(4), dbCmd.lt(32))
  }
})

正则表达式查询

db.RegExp 根据正则表达式进行筛选

例如下面可以筛选出 version 字段开头是 “数字+s” 的记录,并且忽略大小写:

// 可以直接使用正则表达式
db.collection(articles).where({
          
   
  version: /^ds/i
})

// 也可以使用new RegExp
db.collection(user).where({
          
   
  name: new RegExp(^\ds, i)
})

查询数组字段

//指定下标查询
//students字段中第2个元素=wang
const index = 1
const res = await db.collection(class).where({
          
   
  [students. + index]: wang
})
.get()

//不指定下标查询
//students字段中包含wang元素
const res = await db.collection(class).where({
          
   
  students: wang
})
.get()

更新数组内匹配条件的元素

//注意:只可确定数组内只会被匹配到一个的时候使用

const res = await db.collection(query).where({
          
   
    students.id: 001
}).update({
          
   
  // 将students内id为001的name改为li,$代表where内匹配到的数组项的序号
    students.$.name: li
})

数组尾部追加元素

//push
//向数组尾部追加元素,支持传入单个元素或数组
const dbCmd = db.command

let res = await db.collection(comments).doc(comment-id).update({
          
   
  // users: dbCmd.push(aaa)
  users: dbCmd.push([c, d])
})

//pop
//删除数组尾部元素

const dbCmd = db.command

let res = await db.collection(comments).doc(comment-id).update({
          
   
  users: dbCmd.pop()
})
经验分享 程序员 微信小程序 职场和发展