uniapp学习笔记之数据库常用操作
2021/12/20 2:22:33
本文主要是介绍uniapp学习笔记之数据库常用操作,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
日期进行比较操作
//可以使用聚合操作符将日期进行转化,比如以下示例查询所有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() })
这篇关于uniapp学习笔记之数据库常用操作的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-15鸿蒙生态设备数量超8亿台
- 2024-05-13TiDB + ES:转转业财系统亿级数据存储优化实践
- 2024-05-09“2024鸿蒙零基础快速实战-仿抖音App开发(ArkTS版)”实战课程已上线
- 2024-05-09聊聊如何通过arthas-tunnel-server来远程管理所有需要arthas监控的应用
- 2024-05-09log4j2这么配就对了
- 2024-05-09nginx修改Content-Type
- 2024-05-09Redis多数据源,看这篇就够了
- 2024-05-09Google Chrome驱动程序 124.0.6367.62(正式版本)去哪下载?
- 2024-05-09有没有大佬知道这种数据应该怎么抓取呀?
- 2024-05-09这种运行结果里的10.100000001,怎么能最快改成10.1?